<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use App\Models\ResourceModel\CloudhouseCustomSkuModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Models\ResourceModel\ContractModel;
use App\Models\ResourceModel\CustomSkuModel;
use App\Models\ResourceModel\GoodsTransfersModel;
use App\Models\ResourceModel\GoodTransfersDetailModel;
use App\Models\ResourceModel\SpuModel;
class CloudHouse extends BaseModel
{
    const WAREHOUSE = [
        1 => "同安仓",
        2 => "泉州仓",
        3 => "云仓",
        4 => "工厂虚拟仓",
        5 => "其他"
    ];
    protected $contractModel;
    protected $goodsTransfersModel;
    protected $goodsTransfersDetailModel;
    protected $contractSkuModel;
    protected $customSkuModel;
    protected $spuModel;
    protected $saiheWarehouseModel;

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        $this->contractModel = new ContractModel();
        $this->goodsTransfersModel = new GoodsTransfersModel();
        $this->goodsTransfersDetailModel = new GoodTransfersDetailModel();
        $this->contractSkuModel = new CloudhouseCustomSkuModel();
        $this->customSkuModel = new CustomSkuModel();
        $this->spuModel = new SpuModel();
        $this->saiheWarehouseModel = new SaiheWarehouse();
    }

    public function ContractImport($params){
        ////获取Excel文件数据
        $file = $params['file'];

        $contract_no = $params['contract_no'];
        $is_repeat = DB::table('cloudhouse_contract')->where('contract_no',$contract_no)->first();
//        if($is_repeat){
//            return [
//                'type' => 'fail',
//                'msg' => '导入失败，合同号重复'
//            ];
//        }

        $user_id = $params['user_id'];
        $sign_date = $params['sign_date'];

        //获取文件后缀名
        $extension = $file->getClientOriginalExtension();
        if ($extension == 'csv') {
            $PHPExcel = new \PHPExcel_Reader_CSV();
        } elseif ($extension == 'xlsx') {
            $PHPExcel = new \PHPExcel_Reader_Excel2007();
        } else {
            $PHPExcel = new \PHPExcel_Reader_Excel5();
        }

        if (!$PHPExcel->canRead($file)) {
            return [
                'type' => 'fail',
                'msg' => '导入失败，Excel文件错误'
            ];
        }

        $PHPExcelLoad = $PHPExcel->load($file);
        $Sheet = $PHPExcelLoad->getSheet(0);
        $add_list = array();
        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();

        //获取列数
        for ($i=0; $i < 30; $i++) {
            $res = trim($Sheet->getCellByColumnAndRow($i, 1)->getValue());
            if($res=='下单颜色'){
                $start = $i;
            }
            if($res=='合计'){
                $end = $i;
            }
        }


        //获取尺码标题
        $sizes = array();

        for ($si=$start+1; $si < $end; $si++) {
            $sizes[$si] = trim($Sheet->getCellByColumnAndRow($si, 2)->getValue());
        }

        for ($j = 3; $j <= $allRow; $j++) {

            $spu = trim($Sheet->getCellByColumnAndRow(0, $j)->getValue());
            if($spu){
                $add_list[$j - 3]['spu'] = $spu;
                $color = trim($Sheet->getCellByColumnAndRow(2, $j)->getValue());

                try {
                    //code...
                    $colors = explode('/', $color);
                    $add_list[$j - 3]['color_name'] = $colors[0];
                    $add_list[$j - 3]['color_identifying'] = $colors[1];
                } catch (\Throwable $th) {
                    //throw $th;
                    return [
                        'type' => 'fail',
                        'msg' => 's'.$spu.'解析颜色错误，请检查颜色列数是否为第三列，且中英文是否用/符号隔开'.$color
                    ];
                }

                $color_identifying = Db::table('self_color_size')->where('identifying',$add_list[$j - 3]['color_identifying'])->select('identifying')->first();
                if(!$color_identifying){
                    return [
                        'type' => 'fail',
                        'msg' => '无此颜色，请检查是否填写错误'.$color
                    ];
                }
                foreach ($sizes as $key => $value) {
                    # code...
                    //尺码
                    $add_list[$j - 3][$value] = (int)trim($Sheet->getCellByColumnAndRow($key, $j)->getValue());

                    if($add_list[$j - 3][$value]>0){
                        //如果尺码大于0
                        //查询库存sku 并将其存入库存sku表
                        $spus = Db::table('self_spu')->where('spu',$add_list[$j - 3]['spu'])->orwhere('old_spu',$add_list[$j - 3]['spu'])->select('spu','old_spu')->first();
                        if(!$spus){
                            return [
                                'type' => 'fail',
                                'msg' => '无此spu，请检查是否填写错误'.$add_list[$j - 3]['spu']
                            ];
                        }else{
    //                         DB::connection()->enableQueryLog();

                            $new_old_spu = $this->GetSpus($spus->spu);

                            $customres = Db::table('self_custom_sku')->where('color',$color_identifying->identifying)->where('size',$value)->whereIn('spu',$new_old_spu)->select('custom_sku')->first();
                           
    //                         print_r(DB::getQueryLog());
                            if(!$customres){
                                return [
                                    'type' => 'fail',
                                    'msg' => '无此库存sku:'.$add_list[$j - 3]['spu'].'--color:'.$color_identifying->identifying.'--size:'.$value
                                ];
                            }
                        }
                        
                    }
                }

            }
        }


        $customskus = array();
        $spulist = array();
        $total_add = array();
        $total_price = 0;
        $total_count = 0;
        for ($j = 3; $j <= $allRow; $j++) {
            $spu = trim($Sheet->getCellByColumnAndRow(0, $j)->getValue());
            if($spu){
                $spulist[] = $spu;
                //款号
                $add_list[$j - 3]['spu'] =$spu;
                //名字
                $add_list[$j - 3]['title'] = trim($Sheet->getCellByColumnAndRow(1, $j)->getValue());
                //颜色
                $colors = trim($Sheet->getCellByColumnAndRow(2, $j)->getValue());

                try {
                    //code...
                    $colors = explode('/', $colors);
                    $add_list[$j - 3]['color_name'] = $colors[0];
                    $add_list[$j - 3]['color_identifying'] = $colors[1];
                } catch (\Throwable $th) {
                    //throw $th;
                    return [
                        'type' => 'fail',
                        'msg' => 's'.$spu.'解析颜色错误，请检查颜色列数是否为第三列，且中英文是否用/符号隔开'.$spu.$add_list[$j - 3]['color']
                    ];
                }

                $color_identifying = Db::table('self_color_size')->where('identifying',$add_list[$j - 3]['color_identifying'])->select('identifying')->first();
                if(!$color_identifying){
                    return [
                        'type' => 'fail',
                        'msg' => '无此颜色，请检查是否填写错误'.$add_list[$j - 3]['color']
                    ];
                }

                $count = 0;
                db::beginTransaction();    //开启事务
                foreach ($sizes as $key => $value) {
                    # code...
                    //尺码
                    $add_list[$j - 3][$value] = (int)trim($Sheet->getCellByColumnAndRow($key, $j)->getValue());

                    if($add_list[$j - 3][$value]>0){
                        //如果尺码大于0
                        //查询库存sku 并将其存入库存sku表
                        $spus = Db::table('self_spu')->where('spu',$add_list[$j - 3]['spu'])->orwhere('old_spu',$add_list[$j - 3]['spu'])->select('spu','old_spu')->first();
                        if(!$spus){
                            return [
                                'type' => 'fail',
                                'msg' => '无此spu，请检查是否填写错误'.$add_list[$j - 3]['spu']
                            ];
                        }else{
                            // DB::connection()->enableQueryLog();

                            $new_old_spu = $this->GetSpus($spus->spu);

                            $customres = Db::table('self_custom_sku')->where('color',$color_identifying->identifying)->where('size',$value)->whereIn('spu',$new_old_spu)->select('custom_sku','old_custom_sku','spu_id','id')->first();
                            // print_r(DB::getQueryLog());
                            if(!$customres){
                                db::rollback();// 回调
                                return [
                                    'type' => 'fail',
                                    'msg' => '无此库存sku:'.$add_list[$j - 3]['spu'].$add_list[$j - 3][$value].'--size:'.$value
                                ];
                            }else{
                                $customskus[] = $customres->custom_sku;
                                $cusinsert['spu_id'] = $customres->spu_id;
                                $cusinsert['custom_sku_id'] = $customres->id;
                                $cusinsert['spu'] = $add_list[$j - 3]['spu'];
                                $cusinsert['size'] = $value;
                                $cusinsert['num'] = $add_list[$j - 3][$value];
                                $cusinsert['color'] = $color_identifying->identifying;
                                $cusinsert['custom_sku'] = $customres->old_custom_sku??$customres->custom_sku;
                                $cusinsert['contract_no'] = $contract_no;
                                $cusinsert['color_name'] = $add_list[$j - 3]['color_name'];
                                Db::table('cloudhouse_custom_sku')->insert($cusinsert);
                            }
                        }
                        
                    }
                    $count+= $add_list[$j - 3][$value];
                }
                db::commit();
                //合计
                $add_list[$j - 3]['count'] =  $count;
                //单价
                $price = trim($Sheet->getCellByColumnAndRow($end+1, $j)->getValue());
                $add_list[$j - 3]['one_price'] = $price;
                //金额
                $add_list[$j - 3]['price'] =  round($count*$add_list[$j - 3]['one_price'],4);
                //品牌
                $add_list[$j - 3]['brand'] = trim($Sheet->getCellByColumnAndRow($end+3, $j)->getValue());
                //交货期
                $date = $Sheet->getCellByColumnAndRow($end+4, $j)->getValue();
                // $add_list[$j - 3]['report_date'] = $Sheet->getCellByColumnAndRow($end+4, $j)->getValue();
                if (is_numeric($date)){
                    $t1 = intval(($date - 25569) * 3600 * 24); //转换成1970年以来的秒数
                    $date = gmdate('Y-m-d',$t1);
                }
                $add_list[$j - 3]['spu_id'] = $customres->spu_id;
                $add_list[$j - 3]['report_date'] = $date;
                $add_list[$j - 3]['contract_no'] =  $contract_no;
                $add_list[$j - 3]['type'] =  1;
                $add_list[$j - 3]['status'] =  1;
                $add_list[$j - 3]['create_user'] =  $user_id;
                $add_list[$j - 3]['sign_date'] =  $sign_date;
                $add_list[$j - 3]['create_time'] = date('Y-m-d H:i:s',time());

                $total_price += $add_list[$j - 3]['price'];
                $total_count += $count;
            }
        }
        $spulist = array_unique($spulist);
        $total_add['spu_count'] = count($spulist);
        $total_add['sign_date'] = $sign_date;
        $total_add['contract_no'] = $contract_no;
        $total_add['report_date'] = $date;
        $total_add['create_time'] = date('Y-m-d H:i:s');
        $total_add['total_price'] = $total_price;
        $total_add['total_count'] = $total_count;


        $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
        try {
            $cloud::sendJob($customskus);
        } catch(\Exception $e){
            Redis::Lpush('send_goods_fail',json_encode($params));
        }
        $res = Db::table('cloudhouse_contract')->insert($add_list);
        $total_res = Db::table('cloudhouse_contract_total')->insert($total_add);
        return ['type'=>'success','msg'=>'导入成功'];
    }


    public function ContractOutImport($params){
        ////获取Excel文件数据
        $file = $params['file'];

        //获取文件后缀名
        $extension = $file->getClientOriginalExtension();
        if ($extension == 'csv') {
            $PHPExcel = new \PHPExcel_Reader_CSV();
        } elseif ($extension == 'xlsx') {
            $PHPExcel = new \PHPExcel_Reader_Excel2007();
        } else {
            $PHPExcel = new \PHPExcel_Reader_Excel5();
        }

        if (!$PHPExcel->canRead($file)) {
            return [
                'type' => 'fail',
                'msg' => '导入失败，Excel文件错误'
            ];
        }

        $PHPExcelLoad = $PHPExcel->load($file);
        $Sheet = $PHPExcelLoad->getSheet(0);
        $add_list = array();
        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();

        $sizes = [];
        $change = [];
        //取得尺码表头
        for ($i=5; $i < 20; $i++) { 
            # code...
            $size = trim($Sheet->getCellByColumnAndRow($i, 2)->getValue());
            if(!empty($size)){
                $sizes[$i] = $size;
                $change[] = ['name'=>$size,'value'=>$size];
            }
        }

        

        for ($j = 3; $j <= $allRow; $j++) {
            if(!$Sheet->getCellByColumnAndRow(0, $j)->getValue()){
               continue;
            }
            $add_list[$j - 3]['contract_no'] = trim($Sheet->getCellByColumnAndRow(0, $j)->getValue());
            $add_list[$j - 3]['spu'] = trim($Sheet->getCellByColumnAndRow(1, $j)->getValue());

            // if($params['type']=='shipment'){
                $add_list[$j - 3]['brand'] = trim($Sheet->getCellByColumnAndRow(2, $j)->getValue());
                $add_list[$j - 3]['box_id'] = trim($Sheet->getCellByColumnAndRow(4, $j)->getValue());
                $colors = trim($Sheet->getCellByColumnAndRow(3, $j)->getValue());
                foreach ($sizes as $sk => $sv) {
                    # code...
                    $add_list[$j - 3][$sv] = (int)trim($Sheet->getCellByColumnAndRow($sk, $j)->getValue())??0;
                }
                // $add_list[$j - 2]['XXS'] = (int)trim($Sheet->getCellByColumnAndRow(5, $j)->getValue());
                // $add_list[$j - 2]['XS'] = (int)trim($Sheet->getCellByColumnAndRow(6, $j)->getValue())??0;
                // $add_list[$j - 2]['S'] = (int)trim($Sheet->getCellByColumnAndRow(7, $j)->getValue())??0;
                // $add_list[$j - 2]['M'] = (int)trim($Sheet->getCellByColumnAndRow(8, $j)->getValue())??0;
                // $add_list[$j - 2]['L'] = (int)trim($Sheet->getCellByColumnAndRow(9, $j)->getValue())??0;
                // $add_list[$j - 2]['XL'] = (int)trim($Sheet->getCellByColumnAndRow(10, $j)->getValue())??0;
                // $add_list[$j - 2]['2XL'] = (int)trim($Sheet->getCellByColumnAndRow(11, $j)->getValue())??0;
                // $add_list[$j - 2]['3XL'] = (int)trim($Sheet->getCellByColumnAndRow(12, $j)->getValue())??0;
                // $add_list[$j - 2]['4XL'] = (int)trim($Sheet->getCellByColumnAndRow(13, $j)->getValue())??0;
                // $add_list[$j - 2]['5XL'] = (int)trim($Sheet->getCellByColumnAndRow(14, $j)->getValue())??0;
                // $add_list[$j - 2]['6XL'] = (int)trim($Sheet->getCellByColumnAndRow(15, $j)->getValue())??0;
                // $add_list[$j - 2]['7XL'] = (int)trim($Sheet->getCellByColumnAndRow(16, $j)->getValue())??0;
                // $add_list[$j - 2]['8XL'] = (int)trim($Sheet->getCellByColumnAndRow(17, $j)->getValue())??0;
            // }
            // if($params['type']=='production'){
            //     $colors = trim($Sheet->getCellByColumnAndRow(2, $j)->getValue());
            //     $add_list[$j - 2]['XXS'] = (int)trim($Sheet->getCellByColumnAndRow(4, $j)->getValue());
            //     $add_list[$j - 2]['XS'] = (int)trim($Sheet->getCellByColumnAndRow(5, $j)->getValue())??0;
            //     $add_list[$j - 2]['S'] = (int)trim($Sheet->getCellByColumnAndRow(6, $j)->getValue())??0;
            //     $add_list[$j - 2]['M'] = (int)trim($Sheet->getCellByColumnAndRow(7, $j)->getValue())??0;
            //     $add_list[$j - 2]['L'] = (int)trim($Sheet->getCellByColumnAndRow(8, $j)->getValue())??0;
            //     $add_list[$j - 2]['XL'] = (int)trim($Sheet->getCellByColumnAndRow(9, $j)->getValue())??0;
            //     $add_list[$j - 2]['2XL'] = (int)trim($Sheet->getCellByColumnAndRow(10, $j)->getValue())??0;
            //     $add_list[$j - 2]['3XL'] = (int)trim($Sheet->getCellByColumnAndRow(11, $j)->getValue())??0;
            //     $add_list[$j - 2]['4XL'] = (int)trim($Sheet->getCellByColumnAndRow(12, $j)->getValue())??0;
            //     $add_list[$j - 2]['5XL'] = (int)trim($Sheet->getCellByColumnAndRow(13, $j)->getValue())??0;
            //     $add_list[$j - 2]['6XL'] = (int)trim($Sheet->getCellByColumnAndRow(14, $j)->getValue())??0;
            //     $add_list[$j - 2]['7XL'] = (int)trim($Sheet->getCellByColumnAndRow(15, $j)->getValue())??0;
            //     $add_list[$j - 2]['8XL'] = (int)trim($Sheet->getCellByColumnAndRow(16, $j)->getValue())??0;
            // }
            

            try {
                //code...
                $colorss = explode('/', $colors);
                $add_list[$j - 3]['color_name'] = $colorss[0];
                $add_list[$j - 3]['color_identifying'] = $colorss[1];
            } catch (\Throwable $th) {
                
                throw $th;
                return [
                    'type' => 'fail',
                    'msg' =>  $colors.'颜色异常'.$j
                ];
            }

            // try {
            //     //code...
            //     $color_en = explode('/',$add_list[$j - 2]['color'])[1];
            // } catch (\Throwable $th) {
            //     //throw $th;
            //     return [
            //         'type' => 'fail',
            //         'msg' =>  $add_list[$j - 2]['color'].'颜色异常'.$j
            //     ];
            // }
            // echo $color_en;
            $res = Db::table('cloudhouse_contract')->where('contract_no',$add_list[$j - 3]['contract_no'])->where('spu',$add_list[$j - 3]['spu'])->Where('color_identifying',$add_list[$j - 3]['color_identifying'])->first();

            $query['spu'] = $add_list[$j - 3]['spu'];
            $query['color'] = $colors;
            $query['contract_no'] = $add_list[$j - 3]['contract_no'];

            if(!$res){
                return [
                    'type' => 'fail',
                    'msg' => '导入失败，无此合同或颜色或spu--spu:'.$query['spu'] .'--合同号：'.$query['contract_no'].'--颜色：'.$query['color']
                ]; 
            }
            // $add_list[$j - 2]['color'] = $res->color;
        }

        $add_list = array_values($add_list);

        return ['type'=>'success','msg'=>'导入成功','data'=>$add_list,'change'=>$change];

    }





    //走柜
    public function ContractZgImport($params){
        ////获取Excel文件数据
        $file = $params['file'];

        //获取文件后缀名
        $extension = $file->getClientOriginalExtension();
        if ($extension == 'csv') {
            $PHPExcel = new \PHPExcel_Reader_CSV();
        } elseif ($extension == 'xlsx') {
            $PHPExcel = new \PHPExcel_Reader_Excel2007();
        } else {
            $PHPExcel = new \PHPExcel_Reader_Excel5();
        }

        if (!$PHPExcel->canRead($file)) {
            return [
                'type' => 'fail',
                'msg' => '导入失败，Excel文件错误'
            ];
        }

        $PHPExcelLoad = $PHPExcel->load($file);
        $Sheet = $PHPExcelLoad->getSheet(0);
        $add_list = array();
        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();
        


        for ($j = 3; $j <= $allRow; $j++) {
            $add_list[$j - 3]['contract_no'] = trim($Sheet->getCellByColumnAndRow(1, $j)->getValue());
            $add_list[$j - 3]['custom_sku'] = trim($Sheet->getCellByColumnAndRow(2, $j)->getValue());
            // $add_list[$j - 2]['size'] = trim($Sheet->getCellByColumnAndRow(6, $j)->getValue());
            $add_list[$j - 3]['num'] = trim($Sheet->getCellByColumnAndRow(9, $j)->getValue());
            $add_list[$j - 3]['box_num'] = trim($Sheet->getCellByColumnAndRow(10, $j)->getValue());

            $cus = Db::table('self_custom_sku')->where('custom_sku',$add_list[$j - 3]['custom_sku'])->first();
            if(!$cus){
                return [
                    'type' => 'fail',
                    'msg' => '导入失败,无此库存sku'.$add_list[$j - 3]['custom_sku']
                ];
            }


            $spu = $this->GetOldSpu($cus->spu);
            $size = $cus->size;

            // $colors = Db::table('self_color_size')->where('identifying',$cus->color)->first();
            // if($colors){
            //     $color = $colors->name.'/'.$colors->english_name;

            // }

            // if(!$color){
            //     return [
            //         'type' => 'fail',
            //         'msg' => '导入失败,此库存spu无对应颜色'.$add_list[$j - 3]['custom_sku']
            //     ];
            // }

            $is_contract = Db::table('cloudhouse_contract')->where('contract_no',$add_list[$j - 3]['contract_no'])->where('spu',$spu)->where('color_identifying',$cus->color)->first();

            if(!$is_contract){
                return [
                    'type' => 'fail',
                    'msg' => '导入失败,无此合同spu:'.$spu.'--color:'.$cus->color.'--合同号:'.$add_list[$j - 3]['contract_no']
                ];
            }
            $add_list[$j - 3]['spu'] = $spu;
            $add_list[$j - 3]['size'] = $size;
            $add_list[$j - 3]['color_identifying'] = $cus->color;

            $add_list[$j - 3]['color_name'] = $is_contract->color_name;


        }

        $newdata = [];


        //根据spu 颜色分组
        foreach ($add_list as $v) {
            # code...
            $spu_one['size']= $v['size'];
            $spu_one['num']= $v['num'];
            $key = $v['spu'].$v['color'];
            $newdata[$key][] = $spu_one;
        }

        $data = [];

        $ki=0;
        foreach ($newdata as $nk => $nv) {
            # code...
            $return = [];
            $cus = [];
            $boxs = [];
            foreach ($add_list as $ak => $av) {
                # code...
                 $key = $av['spu'].$av['color'];
                 if($key== $nk){

                    //箱号
                    $box = explode("-",$av['box_num']);

                    if(isset($box[1])){
                        $start = $box[0];
                        $end = $box[1];
                        for ($i=$start; $i < $end+1;$i++) { 
                            # code...
                            $boxs[$i] = 1;
                        }
                       
                    }else{
                        $boxs[$av['box_num']] = 1;
                    }

                    
                    
                    $return = $add_list[$ak];
                    $cus[] = $av['custom_sku'];
                    $return['XS'] = 0;
                    $return['S'] = 0;
                    $return['M'] = 0;
                    $return['L'] = 0;
                    $return['XL'] = 0;
                    $return['2XL'] = 0;
                    $return['3XL'] = 0;
                    $return['4XL'] = 0;
                    $return['5XL'] = 0;
                    $num = 0;
                    //尺寸
                    foreach ($nv as $evv) {
                        # code...
                        $size = $evv['size'];
                        $return[$size] = (int)$evv['num'];
                    }

                 }
            }
            $return['box_id'] = array_keys($boxs);
            $return['cus'] = $cus;
            $data[$ki] =  $return;
            $ki++;
        }


        return ['type'=>'success','msg'=>'导入成功','data'=>$data];
    }



    public function GetContractColor($params){

        $list = Db::table('cloudhouse_contract');
        if(isset($params['spu'])){
            $list = $list->where('spu','like','%'.$params['spu'].'%');
        }
        if (isset($params['contract_no'])) {
            $list = $list->where('contract_no','like','%'.$params['contract_no'].'%');
        }
        $list = $list->groupBy('color_name')->get(['color_name','color_identifying']);
        // foreach ($list  as $v) {
        //     # code...
        //     $v->color = $v->color_name.'/'.$v->color_identifying;
        // }
        return ['type'=>'success','data'=>$list];
    }

    //合同订单列表
    public function ContractList($params){

        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        // $where['status'] = 1;

        //类型1合同 2出库
        $where['type'] = 1;

        $list = Db::table('cloudhouse_contract')->where('status','!=',0);
        

        if (isset($params['spu'])) {
            $query_spus = array();
            if (strstr($params['spu'], '，')) {
                $symbol = '，';
            } elseif (strstr($params['spu'], ',')) {
                $symbol = ',';
            } else {
                $symbol = '';
            }
            if ($symbol) {
                $spu_skuarray = explode($symbol,$params['spu']);
                foreach ($spu_skuarray as $key => $spu) {
                    $query_spus[] = $spu;
                }
                $list = $list->whereIn('spu',$query_spus);
            }else {
                $list = $list->where('spu',$params['spu']);
            }

        }


        if (isset($params['contract_no'])) {
            $query_c = array();
            if (strstr($params['contract_no'], '，')) {
                $symbol = '，';
            } elseif (strstr($params['contract_no'], ',')) {
                $symbol = ',';
            } else {
                $symbol = '';
            }
            if ($symbol) {
                $c_array = explode($symbol,$params['contract_no']);
                foreach ($c_array as $key => $c) {
                    $query_c[] = $c;
                }
                $list = $list->whereIn('contract_no',$query_c);
            }else {
                $list = $list->where('contract_no',$params['contract_no']);
            }

        }

        if (isset($params['color'])) {
            $list = $list->whereIn('color_identifying',$params['color']);
        }

        // if(isset($params['spu'])){
        //     $where['spu'] = $params['spu'];
        // }
        // if(isset($params['contract_no'])){
        //     $where['contract_no'] = $params['contract_no'];
        // }


        $list = $list->where($where);

        if(isset($params['start_time'])&&isset($params['end_time'])){
            $list = $list->whereBetween('report_date', [$params['start_time'], $params['end_time']]);
        }


        $totalNum = $list ->count();
        $list = $list->offset($page)->limit($limit)->orderBy('create_time','desc')->get()->map(function($value){
            return(array)$value;
        })->toArray();

        $newlist = array();
        $checkArr = array();
        $i = 0;
        foreach ($list as $k=>$v) {
//            $checkArr[$v['contract_no'][$v['spu_id']][$v['color_identifying']]] = $k;
//            if(isset($checkArr[$v['contract_no'][$v['spu_id']][$v['color_identifying']]])){
//
//                unset($list[$k]);
//                continue;
//            }
            # code...
            $newlist[$i]['id'] = $v['id'];
            $newlist[$i]['spu'] = $v['spu'];
            $newlist[$i]['spu_id'] = $v['spu_id'];
            $newlist[$i]['title'] = $v['title'];
            $newlist[$i]['color_name'] = $v['color_name'];
            $newlist[$i]['color_identifying'] = $v['color_identifying'];
            $newlist[$i]['count'] = $v['count'];
            $newlist[$i]['one_price'] = $v['one_price'];
            $newlist[$i]['price'] = $v['price'];
            $newlist[$i]['brand'] = $v['brand'];
            $newlist[$i]['report_date'] = $v['report_date'];
            $newlist[$i]['contract_no'] = $v['contract_no'];
            $newlist[$i]['create_user'] = $v['create_user'];
            $newlist[$i]['sign_date'] = $v['sign_date'];
            // $newlist[$i]['create_user'] = $this->GetUsers($v['create_user'])['account'];

            // $out_num = Db::table('cloudhouse_contract')->where('spu',$v['spu'])->where('contract_no',$v['contract_no'])->where('type',2)->where('is_push','!=',3)->get()->map(function($value){
            //     return(array)$value;
            // })->toArray();

            $out_num =  Db::table('goods_transfers_detail')->where('spu',$v['spu'])->where('contract_no',$v['contract_no'])->get();
            // var_dump( $out_num );
            if($out_num){

                //将尺码转化为库存sku
                $customres = Db::table('cloudhouse_custom_sku')->where('spu_id',$v['spu_id'])->where('color', $v['color_identifying'])->where('contract_no',$v['contract_no'])->get();
                $sizecus = array();
                $sizecus['XXS'] = '';
                $sizecus['XS'] = '';
                $sizecus['S'] = '';
                $sizecus['M'] = '';
                $sizecus['L'] = '';
                $sizecus['XL'] = '';
                $sizecus['2XL'] = '';
                $sizecus['3XL'] = '';
                $sizecus['4XL'] = '';
                $sizecus['5XL'] = '';
                $sizecus['6XL'] = '';
                $sizecus['7XL'] = '';
                $sizecus['8XL'] = '';

                // var_dump( $customres);


                foreach ($customres as $key => $value) {
                    # code...
                    $sizecus[$value->size] = $value->custom_sku_id;
                }
                // var_dump($sizecus);

                $XXS = 0;
                $XS = 0;
                $S = 0;
                $M = 0;
                $L = 0;
                $XL = 0;
                $XL2 = 0;
                $XL3 = 0;
                $XL4 = 0;
                $XL5 = 0;
                $XL6 = 0;
                $XL7 = 0;
                $XL8 = 0;

                $factoryXXS = 0;
                $factoryXS = 0;
                $factoryS = 0;
                $factoryM = 0;
                $factoryL = 0;
                $factoryXL = 0;
                $factoryXL2 = 0;
                $factoryXL3 = 0;
                $factoryXL4 = 0;
                $factoryXL5 = 0;
                $factoryXL6 = 0;
                $factoryXL7 = 0;
                $factoryXL8 = 0;
                $goodsData = Db::table('goods_transfers')->where('contract_no','like','%'.$v['contract_no'].'%')->whereIn('type',[1,3])->select('order_no','type','back_order_no')->get();

                $outOrder = array();
//                $factoryOrder = array();
                $outBackOrder = array();
                foreach($goodsData as $god){
                    if($god->type==1){
                        if($god->back_order_no){
                            $outBackOrder[] = $god->back_order_no;
                        }
                        $outOrder[] = $god->order_no;
                    }
//                    if($god->type==3){
//                        $factoryOrder[] = $god->order_no;
//                    }
                }
//               $factoryOrder = array_unique($factoryOrder);
                if($sizecus['XXS']!=''){
                    $XXS_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['XXS'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outOrder)->select('receive_num')->get();
                    $XXS_back_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['XXS'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outBackOrder)->select('receive_num')->get();
//                    $XXS_factory = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['XXS'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$factoryOrder)->select('receive_num')->get();
                    if(!empty($XXS_data)){
                        foreach ($XXS_data as $xxs_val){
                            $XXS += $xxs_val->receive_num;
                        }
                    }
                    if(!empty($XXS_back_data)){
                        foreach ($XXS_back_data as $xxs_val2){
                            $XXS -= $xxs_val2->receive_num;
                        }
                    }
//                   if(!empty($XXS_factory)){
//                       foreach ($XXS_factory as $xxs_fval){
//                           $factoryXXS += $xxs_fval->receive_num;
//                       }
//                   }
                }

                if($sizecus['XS']!=''){
                    $XS_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['XS'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outOrder)->select('receive_num')->get();
                    $XS_back_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['XS'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outBackOrder)->select('receive_num')->get();
//                    $XS_factory = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['XS'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$factoryOrder)->select('receive_num')->get();
                    if(!empty($XS_data)){
                        foreach ($XS_data as $xs_val){
                            $XS += $xs_val->receive_num;
                        }
                    }
                    if(!empty($XS_back_data)){
                        foreach ($XS_back_data as $xs_val2){
                            $XS -= $xs_val2->receive_num;
                        }
                    }
//                    if(!empty($XS_factory)){
//                        foreach ($XS_factory as $xs_fval){
//                            $factoryXS += $xs_fval->receive_num;
//                        }
//                    }
                }
   
                if($sizecus['S']!=''){
                    $S_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['S'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outOrder)->select('receive_num')->get();
                    $S_back_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['S'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outBackOrder)->select('receive_num')->get();
//                    $S_factory = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['S'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$factoryOrder)->select('receive_num')->get();
                    if(!empty($S_data)){
                        foreach ($S_data as $s_val){
                            $S += $s_val->receive_num;
                        }
                    }
                    if(!empty($S_back_data)){
                        foreach ($S_back_data as $s_val2){
                            $S -= $s_val2->receive_num;
                        }
                    }
//                    if(!empty($S_factory)){
//                        foreach ($S_factory as $s_fval){
//                            $factoryS += $s_fval->receive_num;
//                        }
//                    }
                }

                if($sizecus['M']!=''){
                    $M_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['M'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outOrder)->select('receive_num')->get();
                    $M_back_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['M'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outBackOrder)->select('receive_num')->get();
//                    $M_factory = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['M'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$factoryOrder)->select('receive_num')->get();
                    if(!empty($M_data)){
                        foreach ($M_data as $m_val){
                            $M += $m_val->receive_num;
                        }
                    }
                    if(!empty($M_back_data)){
                        foreach ($M_back_data as $m_val2){
                            $M -= $m_val2->receive_num;
                        }
                    }
//                    if(!empty($M_factory)){
//                        foreach ($M_factory as $m_fval){
//                            $factoryM += $m_fval->receive_num;
//                        }
//                    }
                }
                if($sizecus['L']!=''){
//                     DB::connection()->enableQueryLog();
                    $L_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['L'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outOrder)->select('receive_num')->get();
                    $L_back_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['L'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outBackOrder)->select('receive_num')->get();
//                    $L_factory = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['L'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$factoryOrder)->select('receive_num')->get();

//                     print_r(DB::getQueryLog());
                    if(!empty($L_data)){
                        foreach ($L_data as $l_val){
                            $L += $l_val->receive_num;
                        }
                    }
                    if(!empty($L_back_data)){
                        foreach ($L_back_data as $l_val2){
                            $L -= $l_val2->receive_num;
                        }
                    }
                    
//                    if(!empty($L_factory)){
//                        foreach ($L_factory as $l_fval){
//                            $factoryL += $l_fval->receive_num;
//                        }
//                    }
                }

                if($sizecus['XL']!=''){
                    $XL_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outOrder)->select('receive_num')->get();
                    $XL_back_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outBackOrder)->select('receive_num')->get();
//                    $XL_factory = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$factoryOrder)->select('receive_num')->get();
                    if(!empty($XL_data)){
                        foreach ($XL_data as $xl_val){
                            $XL += $xl_val->receive_num;
                        }
                    }
                    if(!empty($XL_back_data)){
                        foreach ($XL_back_data as $xl_val2){
                            $XL -= $xl_val2->receive_num;
                        }
                    }
//                    if(!empty($XL_factory)){
//                        foreach ($XL_factory as $xl_fval){
//                            $factoryXL += $xl_fval->receive_num;
//                        }
//                    }
                }

                if($sizecus['2XL']!=''){
                    $XL2_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['2XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outOrder)->select('receive_num')->get();
                    $XL2_back_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['2XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outBackOrder)->select('receive_num')->get();
//                    $XL2_factory = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['2XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$factoryOrder)->select('receive_num')->get();
                    if(!empty($XL2_data)){
                        foreach ($XL2_data as $xl2_val){
                            $XL2 += $xl2_val->receive_num;
                        }
                    }
                    if(!empty($XL2_back_data)){
                        foreach ($XL2_back_data as $xl2_val2){
                            $XL2 -= $xl2_val2->receive_num;
                        }
                    }
//                    if(!empty($XL2_factory)){
//                        foreach ($XL2_factory as $xl2_fval){
//                            $factoryXL2 = $xl2_fval->receive_num;
//                        }
//                    }
                }
   
                if($sizecus['3XL']!=''){
                    $XL3_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['3XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outOrder)->select('receive_num')->get();
                    $XL3_back_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['3XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outBackOrder)->select('receive_num')->get();
//                    $XL3_factory = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['3XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$factoryOrder)->select('receive_num')->get();
                    if(!empty($XL3_data)){
                        foreach ($XL3_data as $xl3_val){
                            $XL3 += $xl3_val->receive_num;
                        }
                    }
                    if(!empty($XL3_back_data)){
                        foreach ($XL3_back_data as $xl3_val2){
                            $XL3 -= $xl3_val2->receive_num;
                        }
                    }
//                    if(!empty($XL3_factory)){
//                        foreach ($XL3_factory as $xl3_fval){
//                            $factoryXL3 += $xl3_fval->receive_num;
//                        }
//                    }
                }
  
                if($sizecus['4XL']!=''){
                    $XL4_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['4XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outOrder)->select('receive_num')->get();
                    $XL4_back_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['4XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outBackOrder)->select('receive_num')->get();
//                    $XL4_factory = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['4XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$factoryOrder)->select('receive_num')->get();
                    if(!empty($XL4_data)){
                        foreach ($XL4_data as $xl4_val){
                            $XL4 += $xl4_val->receive_num;
                        }
                    }
                    if(!empty($XL4_back_data)){
                        foreach ($XL4_back_data as $xl4_val2){
                            $XL4 -= $xl4_val2->receive_num;
                        }
                    }
//                    if(!empty($XL4_factory)){
//                        foreach ($XL4_factory as $xl4_fval){
//                            $factoryXL4 = $xl4_fval->receive_num;
//                        }
//                    }
                }

                if($sizecus['5XL']!=''){
                    $XL5_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['5XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outOrder)->select('receive_num')->get();
                    $XL5_back_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['5XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outBackOrder)->select('receive_num')->get();
//                    $XL5_factory = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['5XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$factoryOrder)->select('receive_num')->get();
                    if(!empty($XL5_data)){
                        foreach ($XL5_data as $xl5_val){
                            $XL5 += $xl5_val->receive_num;
                        }
                    }
                    if(!empty($XL5_back_data)){
                        foreach ($XL5_back_data as $xl5_val2){
                            $XL5 -= $xl5_val2->receive_num;
                        }
                    }
//                    if(!empty($XL5_factory)){
//                        foreach ($XL5_factory as $xl5_fval){
//                            $factoryXL5 = $xl5_fval->receive_num;
//                        }
//                    }
                }

                if($sizecus['6XL']!=''){
                    $XL6_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['6XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outOrder)->select('receive_num')->get();
                    $XL6_back_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['6XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outBackOrder)->select('receive_num')->get();
//                    $XL6_factory = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['6XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$factoryOrder)->select('receive_num')->get();
                    if(!empty($XL6_data)){
                        foreach ($XL6_data as $xl6_val){
                            $XL6 += $xl6_val->receive_num;
                        }
                    }
                    if(!empty($XL6_back_data)){
                        foreach ($XL6_back_data as $xl6_val2){
                            $XL6 -= $xl6_val2->receive_num;
                        }
                    }
//                    if(!empty($XL6_factory)){
//                        foreach ($XL6_factory as $xl6_fval){
//                            $factoryXL6 += $xl6_fval->receive_num;
//                        }
//                    }
                }

                if($sizecus['7XL']!=''){
                    $XL7_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['7XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outOrder)->select('receive_num')->get();
                    $XL7_back_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['7XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outBackOrder)->select('receive_num')->get();
//                    $XL7_factory = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['7XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$factoryOrder)->select('receive_num')->get();
                    if(!empty($XL7_data)){
                        foreach ($XL7_data as $xl7_val){
                            $XL7 += $xl7_val->receive_num;
                        }
                    }
                    if(!empty($XL7_back_data)){
                        foreach ($XL7_back_data as $xl7_val2){
                            $XL7 -= $xl7_val2->receive_num;
                        }
                    }
//                    if(!empty($XL7_factory)){
//                        foreach ($XL7_factory as $xl7_fval){
//                            $factoryXL7 += $xl7_fval->receive_num;
//                        }
//                    }
                }

                if($sizecus['8XL']!=''){
                    $XL8_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['8XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outOrder)->select('receive_num')->get();
                    $XL8_back_data = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['8XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$outBackOrder)->select('receive_num')->get();
//                    $XL8_factory = Db::table('goods_transfers_detail')->where('custom_sku_id',$sizecus['8XL'])->where('contract_no',$v['contract_no'])->whereIn('order_no',$factoryOrder)->select('receive_num')->get();
                    if(!empty($XL8_data)){
                        foreach ($XL8_data as $xl8_val){
                            $XL8 += $xl8_val->receive_num;
                        }
                    }
                    if(!empty($XL8_back_data)){
                        foreach ($XL8_back_data as $xl8_val2){
                            $XL8 -= $xl8_val2->receive_num;
                        }
                    }
//                    if(!empty($XL8_factory)){
//                        foreach ($XL8_factory as $xl8_fval){
//                            $factoryXL8 = $xl8_fval->receive_num;
//                        }
//                    }
                }

                $newlist[$i]['total_receive']  = $XXS+$XS+$S+$M+$L+$XL+$XL2+$XL3+$XL4+$XL5+$XL6+$XL7+$XL8;

                // foreach ($out_num as $ov) {
                //     if($sizecus['XXS']!=''&&$ov->custom_sku == $sizecus['XXS']){
                //         $XXS+=$ov->transfers_num;
                //     }

                //     if($sizecus['L']!=''&&$ov->custom_sku == $sizecus['L']){
                //         // exit;
                //         $L+=$ov->transfers_num;
                //     }
                    
                //     $XXS = $sizecus['XXS'];
                //     $XXS+= $ov['XXS'];
                //     $XS+= $ov['XS'];
                //     $S+= $ov['S'];
                //     $M+= $ov['M'];
                //     $L+= $ov['L'];
                //     $XL+= $ov['XL'];
                //     $XL2+= $ov['2XL'];
                //     $XL3+= $ov['3XL'];
                //     $XL4+= $ov['4XL'];
                //     $XL5+= $ov['5XL'];
                //     $XL6+= $ov['6XL'];
                //     $XL7+= $ov['7XL'];
                //     $XL8+= $ov['8XL'];
                // }

//                $newlist[$i]['XXS']['factory'] = $factoryXXS - $XXS;
//                $newlist[$i]['XS']['factory']  =  $factoryXS - $XS;
//                $newlist[$i]['S']['factory']  = $factoryS - $S;
//                $newlist[$i]['M']['factory']  = $factoryM - $M;
//                $newlist[$i]['L']['factory']  = $factoryL - $L;
//                $newlist[$i]['XL']['factory']  = $factoryXL - $XL;
//                $newlist[$i]['2XL']['factory']  = $factoryXL2 - $XL2;
//                $newlist[$i]['3XL']['factory']  = $factoryXL3 - $XL3;
//                $newlist[$i]['4XL']['factory']  = $factoryXL4 - $XL4;
//                $newlist[$i]['5XL']['factory']  = $factoryXL5 - $XL5;
//                $newlist[$i]['6XL']['factory']  = $factoryXL6 - $XL6;
//                $newlist[$i]['7XL']['factory']  = $factoryXL7 - $XL7;
//                $newlist[$i]['8XL']['factory']  = $factoryXL8 - $XL8;

//                $newlist[$i]['XXS']['factory'] = $factoryXXS;
//                $newlist[$i]['XS']['factory']  =  $factoryXS;
//                $newlist[$i]['S']['factory']  = $factoryS;
//                $newlist[$i]['M']['factory']  = $factoryM;
//                $newlist[$i]['L']['factory']  = $factoryL;
//                $newlist[$i]['XL']['factory']  = $factoryXL;
//                $newlist[$i]['2XL']['factory']  = $factoryXL2;
//                $newlist[$i]['3XL']['factory']  = $factoryXL3;
//                $newlist[$i]['4XL']['factory']  = $factoryXL4;
//                $newlist[$i]['5XL']['factory']  = $factoryXL5;
//                $newlist[$i]['6XL']['factory']  = $factoryXL6;
//                $newlist[$i]['7XL']['factory']  = $factoryXL7;
//                $newlist[$i]['8XL']['factory']  = $factoryXL8;

                $XXS = $v['XXS'] - $XXS;
                $XS = $v['XS'] - $XS;
                $S = $v['S'] - $S;
                $M = $v['M'] - $M;
                $L = $v['L'] - $L;
                $XL = $v['XL'] - $XL;
                $XL2 = $v['2XL'] - $XL2;
                $XL3 = $v['3XL'] - $XL3;
                $XL4 = $v['4XL'] - $XL4;
                $XL5 = $v['5XL'] - $XL5;
                $XL6 = $v['6XL'] - $XL6;
                $XL7 = $v['7XL'] - $XL7;
                $XL8 = $v['8XL'] - $XL8;
                
                $newlist[$i]['L']['custom_sku'] = $sizecus['L'];
                $newlist[$i]['XXS']['surplus'] = $XXS;
                $newlist[$i]['XS']['surplus']  =  $XS;
                $newlist[$i]['S']['surplus']  = $S;
                $newlist[$i]['M']['surplus']  = $M;
                $newlist[$i]['L']['surplus']  = $L;
                $newlist[$i]['XL']['surplus']  = $XL;
                $newlist[$i]['2XL']['surplus']  = $XL2;
                $newlist[$i]['3XL']['surplus']  = $XL3;
                $newlist[$i]['4XL']['surplus']  = $XL4;
                $newlist[$i]['5XL']['surplus']  = $XL5;
                $newlist[$i]['6XL']['surplus']  = $XL6;
                $newlist[$i]['7XL']['surplus']  = $XL7;
                $newlist[$i]['8XL']['surplus']  = $XL8;

//                $newlist[$i]['XXS']['show'] = $XXS.'/'.$v['XXS'];
//                $newlist[$i]['XS']['show']  = $XS.'/'.$v['XS'];
//                $newlist[$i]['S']['show']  = $S.'/'.$v['S'];
//                $newlist[$i]['M']['show']  = $M.'/'.$v['M'];
//                $newlist[$i]['L']['show']  = $L.'/'.$v['L'];
//                $newlist[$i]['XL']['show']  = $XL.'/'.$v['XL'];
//                $newlist[$i]['2XL']['show']  = $XL2.'/'.$v['2XL'];
//                $newlist[$i]['3XL']['show']  = $XL3.'/'.$v['3XL'];
//                $newlist[$i]['4XL']['show']  = $XL4.'/'.$v['4XL'];
//                $newlist[$i]['5XL']['show']  = $XL5.'/'.$v['5XL'];
//                $newlist[$i]['6XL']['show']  = $XL6.'/'.$v['6XL'];
//                $newlist[$i]['7XL']['show']  = $XL7.'/'.$v['7XL'];
//                $newlist[$i]['8XL']['show']  = $XL8.'/'.$v['8XL'];
//
                $newlist[$i]['XXS']['show'] = $XXS.'/'.$v['XXS'];
                $newlist[$i]['XS']['show']  = $XS.'/'.$v['XS'];
                $newlist[$i]['S']['show']  = $S.'/'.$v['S'];
                $newlist[$i]['M']['show']  = $M.'/'.$v['M'];
                $newlist[$i]['L']['show']  = $L.'/'.$v['L'];
                $newlist[$i]['XL']['show']  = $XL.'/'.$v['XL'];
                $newlist[$i]['2XL']['show']  = $XL2.'/'.$v['2XL'];
                $newlist[$i]['3XL']['show']  = $XL3.'/'.$v['3XL'];
                $newlist[$i]['4XL']['show']  = $XL4.'/'.$v['4XL'];
                $newlist[$i]['5XL']['show']  = $XL5.'/'.$v['5XL'];
                $newlist[$i]['6XL']['show']  = $XL6.'/'.$v['6XL'];
                $newlist[$i]['7XL']['show']  = $XL7.'/'.$v['7XL'];
                $newlist[$i]['8XL']['show']  = $XL8.'/'.$v['8XL'];
            }else{
                $newlist[$i]['total_receive']  = 0;
                //XXS XS S M L XL 2XL 3XL 4XL 5XL 6XL 7XL 8XL
                $newlist[$i]['XXS']['surplus']  =  $v['XXS'];
                $newlist[$i]['XS']['surplus']  =  $v['XS'];
                $newlist[$i]['S']['surplus']  =  $v['S'];
                $newlist[$i]['M']['surplus']  =  $v['M'];
                $newlist[$i]['L']['surplus']  =  $v['L'];
                $newlist[$i]['XL']['surplus']  =  $v['XL'];
                $newlist[$i]['2XL']['surplus']  =  $v['2XL'];
                $newlist[$i]['3XL']['surplus']  =  $v['3XL'];
                $newlist[$i]['4XL']['surplus']  =  $v['4XL'];
                $newlist[$i]['5XL']['surplus']  =  $v['5XL'];
                $newlist[$i]['6XL']['surplus']  =  $v['6XL'];
                $newlist[$i]['7XL']['surplus']  =  $v['7XL'];
                $newlist[$i]['8XL']['surplus']  =  $v['8XL'];

                $newlist[$i]['XXS']['factory'] = $v['XXS'];
                $newlist[$i]['XS']['factory']  = $v['XS'];
                $newlist[$i]['S']['factory']  = $v['S'];
                $newlist[$i]['M']['factory']  =  $v['M'];
                $newlist[$i]['L']['factory']  = $v['L'];
                $newlist[$i]['XL']['factory']  = $v['XL'];
                $newlist[$i]['2XL']['factory']  = $v['2XL'];
                $newlist[$i]['3XL']['factory']  =  $v['3XL'];
                $newlist[$i]['4XL']['factory']  = $v['4XL'];
                $newlist[$i]['5XL']['factory']  = $v['5XL'];
                $newlist[$i]['6XL']['factory']  = $v['6XL'];
                $newlist[$i]['7XL']['factory']  = $v['7XL'];
                $newlist[$i]['8XL']['factory']  =  $v['8XL'];


                $newlist[$i]['XXS']['show']  =  $v['XXS'].'/'.$v['XXS'];
                $newlist[$i]['XS']['show']  =  $v['XS'].'/'.$v['XS'];
                $newlist[$i]['S']['show']  =  $v['S'].'/'.$v['S'];
                $newlist[$i]['M']['show']  =  $v['M'].'/'.$v['M'];
                $newlist[$i]['L']['show']  =  $v['L'].'/'.$v['L'];
                $newlist[$i]['XL']['show']  =  $v['XL'].'/'.$v['XL'];
                $newlist[$i]['2XL']['show']  =  $v['2XL'].'/'.$v['2XL'];
                $newlist[$i]['3XL']['show']  =  $v['3XL'].'/'.$v['3XL'];
                $newlist[$i]['4XL']['show']  =  $v['4XL'].'/'.$v['4XL'];
                $newlist[$i]['5XL']['show']  =  $v['5XL'].'/'.$v['5XL'];
                $newlist[$i]['6XL']['show']  =  $v['6XL'].'/'.$v['6XL'];
                $newlist[$i]['7XL']['show']  =  $v['7XL'].'/'.$v['7XL'];
                $newlist[$i]['8XL']['show']  =  $v['8XL'].'/'.$v['8XL'];
            }
            $i++;

        }
        return [
            'data' => $newlist,
            'totalNum' => $totalNum,
        ];
    }


    public function SizeBySort($params){
        $sizes = $params['size'];
        // $sizes = db::table('self_color_size')->whereIn('identifying',$sizes)->select('sort','identifying')->orderby('sort')->get();
        $sizes = db::table('self_color_size')->select('sort','identifying')->orderby('sort')->get();
        $data = [];
        foreach ($sizes as $v) {
            # code...
            $data[] = ['name'=>$v->identifying,'value'=>$v->identifying];
        }

        return ['data'=>$data,'msg'=>'获取成功'];
    }

    public function purchase_order_list($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }
        $list = db::table('purchase_order_list');
        if(isset($params['order_id'])){
            $list =  $list ->where('purchaseNumber','like','%'.$params['order_id'].'%');
        }
    
        $totalNum = $list ->count();
        $list = $list->offset($page)->limit($limit)->get();


        return [
            'data' => $list,
            'totalNum' => $totalNum,
        ];

    }

    //合同订单列表
    public function ContractListNew_b($params){

        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        // $where['status'] = 1;

        //类型1合同 2出库


        $list = db::table('purchase_order_list as a')->leftjoin('self_custom_sku as b','a.sku_id','=','b.id')->leftjoin('self_spu as c','b.spu_id','=','c.id');

        
        $totalNum = $list ->count();
        $list = $list
            ->offset($page)->limit($limit)->select([''])->get();

        // if(isset($params['spu'])){
        //     $where['spu'] = $params['spu'];
        // }
        // if(isset($params['contract_no'])){
        //     $where['contract_no'] = $params['contract_no'];
        // }

        // $sizes = db::table('self_color_size')->select('sort','identifying')->orderby('sort')->get();

        // $list = $list->where($where);


        // if(isset($params['start_time'])&&isset($params['end_time'])){
        //     $list = $list->whereBetween('a.report_date', [$params['start_time'], $params['end_time']]);
        //     $allList = $allList->whereBetween('a.report_date', [$params['start_time'], $params['end_time']]);
        // }

        // if (!isset($params['user_id']) || empty($params['user_id'])){
        //     if (isset($params['token']) && !empty($params['token'])){
        //         $users = db::table('users')->where('token',$params['token'])->first();
        //         $params['user_id'] = $users->Id ?? 0;
        //     }else{
        //         $params['user_id'] = 0;
        //     }
        // }

        $controller = new Controller();
        $power = $controller->powers(['user_id' => $params['user_id'], 'identity' => ['show_all_contract_shipment']]);

        $totalNum = $list ->count();
        $list = $list
            ->offset($page)->limit($limit)
            ->select('a.id','a.spu','a.spu_id','b.memo','a.title','a.color_name','a.color_identifying',db::raw('sum(a.count) as count'),'a.one_price',db::raw('sum(a.price) as price'),'a.brand','a.report_date','a.contract_no','a.create_user','a.sign_date','a.num_info', 'a.order_id', 'b.contract_class')
            ->orderBy('a.create_time','desc')
            ->groupBy(['a.contract_no', 'a.spu_id', 'a.color_identifying'])
            ->get();
        $placeOrderMdl = db::table('amazon_place_order_task')
            ->get(['id', 'user_id'])
            ->pluck('user_id', 'id');
        $userMdl = db::table('users')
            ->get(['Id', 'account'])
            ->pluck('account', 'Id');
        $organizeMdl = db::table('organizes_member as a')
            ->leftJoin('organizes as b', 'a.organize_id', '=', 'b.Id')
            ->get(['a.user_id', 'b.name'])
            ->pluck('name', 'user_id');
        $allList = $allList
            ->select('a.contract_no', 'a.num_info', 'a.rule', 'a.spu_id', 'a.color_identifying', 'a.order_id')
            ->get();
        $allSizeList = [];
        foreach ($allList as $all){
            $key = $all->contract_no.'-'.$all->spu_id.'-'.$all->color_identifying;
            $num_info = json_decode($all->num_info, true);
            $rule = explode(',', $all->rule);
            if (isset($allSizeList[$key])){
                $allSizeList[$key]['rule'] = array_unique(array_merge($allSizeList[$key]['rule'], $rule));
                foreach ($rule as $r){
                    if (isset($allSizeList[$key]['num_info'][$r])){
                        $allSizeList[$key]['num_info'][$r] += $num_info[$r] ?? 0;
                    }else{
                        $allSizeList[$key]['num_info'][$r] = $num_info[$r] ?? 0;
                    }
                }
                $allSizeList[$key]['order_id'][] = $all->order_id;
            }else{
                $allSizeList[$key] = [
                    'num_info' => $num_info,
                    'rule' => $rule,
                    'order_id' => [$all->order_id],
                ];
            }
        }

        $rule = [];
        $rules = [];
        $change= [];

        $rules[0] = ['name'=>'id','value'=>'id','sort'=>0];
        $rules[1] = ['name'=>'合同号','value'=>'contract_no','sort'=>0];
        $rules[2] = ['name'=>'款号(SPU)','value'=>'spu','sort'=>0];
        $rules[3] = ['name'=>'下单颜色','value'=>'color_name','sort'=>0];
        $rules[4] = ['name'=>'颜色标识','value'=>'color_identifying','sort'=>0];
        $rules[5] = ['name'=>'交货期','value'=>'report_date','sort'=>0];
        $rules[6] = ['name'=>'品牌','value'=>'brand','sort'=>0];
        $rules[7] = ['name'=>'合同数量','value'=>'count','sort'=>0];
        $rules[8] = ['name'=>'单价(元)(含税)','value'=>'one_price','sort'=>0];
        $rules[9] = ['name'=>'金额(含税)','value'=>'price','sort'=>0];
        $rules[10] = ['name'=>'品名(中/英)','value'=>'title','sort'=>0];
        $rules[11] = ['name'=>'签约时间','value'=>'sign_date','sort'=>0];
        $rules[12] = ['name'=>'采购单号','value'=>'order_id','sort'=>0];
        $rules[13] = ['name'=>'部门','value'=>'organize_name','sort'=>0];
        $rules[14] = ['name'=>'备货人','value'=>'user_name','sort'=>0];

        $customSkuMdl = db::table('self_custom_sku')
            ->get(['id', 'color', 'size', 'spu_id']);
        $customSkuList = [];
        foreach ($customSkuMdl as $cus){
            $key = $cus->spu_id.'-'.$cus->color.'-'.$cus->size;
            $customSkuList[$key] = $cus->id;
        }
        $goods_transfers_detail_mdl = db::table('goods_transfers_detail as a')
            ->leftjoin('goods_transfers as b','a.order_no','=','b.order_no')
//            ->where('b.contract_no','like','%'.$v->contract_no.'%')
            ->whereIn('b.is_push',[1,2,3,4])
           ->where('b.type_detail', 2)
            ->get(['a.*', 'b.is_push']);



        $goods_transfers_detail_md2 = db::table('goods_transfers_detail as a')
        ->leftjoin('goods_transfers as b','a.order_no','=','b.order_no')
//            ->where('b.contract_no','like','%'.$v->contract_no.'%')
        ->whereIn('b.is_push',[1,2,3,4])
        ->where('b.type_detail', 9)
        ->get(['a.*', 'b.is_push']);
        $goodsTransfersDetailList = [];
        foreach ($goods_transfers_detail_mdl as $gd){
            $goodsTransfersDetailList[$gd->contract_no][] = $gd;
        }

        $goodsTransfersDetailListReturn = [];
        if($goods_transfers_detail_md2->isNotEmpty()){
            foreach ($goods_transfers_detail_md2 as $gd){
                $goodsTransfersDetailListReturn[$gd->contract_no][] = $gd;
            }
        }

        if (!isset($params['user_id']) || empty($params['user_id'])){
            if (isset($params['token']) && !empty($params['token'])){
                $users = db::table('users')->where('token',$params['token'])->first();
                if($users){
                    $params['user_id'] = $users->Id;
                }else{
                    $params['user_id'] = 0;
                }
            }else{
                $params['user_id'] = 0;
            }
        }

        foreach ($list as $k => $v) {
            // if (!$power['show_all_contract_shipment'] && $v->contract_class != 3){
            //     if ($v->create_user != $params['user_id']){
            //         unset($list[$k]);
            //         continue;
            //     }
            // }
            // $v->color_itf = $v->color_name.'/'.$v->color_identifying;
            $key = $v->contract_no.'-'.$v->spu_id.'-'.$v->color_identifying;
            if (isset($allSizeList[$key])){
                $v->num_info = json_encode($allSizeList[$key]['num_info']);
                $v->rule = implode(',', $allSizeList[$key]['rule']);
                $v->order_id = implode(',', array_unique($allSizeList[$key]['order_id']));
            }else{
                $v->num_info = '';
                $v->rule = '';
                $v->order_id = '';
            }
            $num_info = json_decode($v->num_info);
            if(!empty($num_info)){
//                $goods_transfers_detail = db::table('goods_transfers_detail as a')->leftjoin('goods_transfers as b','a.order_no','=','b.order_no')->where('b.contract_no','like','%'.$v->contract_no.'%')->whereIn('b.is_push',[1,2,3,4])->get();
                $goods_transfers_detail = $goodsTransfersDetailList[$v->contract_no] ?? [];

                $goods_transfers_detail_return = $goodsTransfersDetailListReturn[$v->contract_no] ?? [];

                $gt_rt_detail = [];

                if(!empty($goods_transfers_detail_return)){
                    foreach ($goods_transfers_detail_return as $gtrdv) {
                        # code...
                        if(isset($gt_rt_detail[$gtrdv->custom_sku_id])){
                            $gt_rt_detail[$gtrdv->custom_sku_id]+=$gtrdv->receive_num;
                        }else{
                            $gt_rt_detail[$gtrdv->custom_sku_id] = $gtrdv->receive_num;
                        }
    
                    }
                }

                //合同数量 
                // 未出货数量 goods_transfers_detail  合同数 - receive_num  状态未完成 = 合同数-transfers_num
                // 已出货待入库数量 transfers_num-receive_num
                // 已入库数量receive_num  type_detail = 2(出货)   - type_detail = 9（退货）
                $un_outnum = [];
                $wait_outnum = [];
                $receive_num = [];
                foreach ($goods_transfers_detail as $g_t_d_v) {
                    # code...
                    //已完成
                    // if($g_t_d_v->is_push==3){
                    if(isset($un_outnum[$g_t_d_v->custom_sku_id])){
                        $un_outnum[$g_t_d_v->custom_sku_id]+=$g_t_d_v->receive_num;
                    }else{
                        $un_outnum[$g_t_d_v->custom_sku_id] = $g_t_d_v->receive_num;
                    }
                    // }else{
                    //     if(isset($un_outnum[$g_t_d_v->custom_sku_id])){
                    //         $un_outnum[$g_t_d_v->custom_sku_id]+=$g_t_d_v->transfers_num;
                    //     }else{
                    //         $un_outnum[$g_t_d_v->custom_sku_id] = $g_t_d_v->transfers_num;
                    //     }
                    // }

                    if(isset($wait_outnum[$g_t_d_v->custom_sku_id])){
                        $wait_outnum[$g_t_d_v->custom_sku_id]+=$g_t_d_v->transfers_num-$g_t_d_v->receive_num;
                    }else{
                        $wait_outnum[$g_t_d_v->custom_sku_id] = $g_t_d_v->transfers_num-$g_t_d_v->receive_num;
                    }


                    // if($g_t_d_v->is_push==3){
                    if(isset($receive_num[$g_t_d_v->custom_sku_id])){
                        $receive_num[$g_t_d_v->custom_sku_id]+=$g_t_d_v->receive_num;
                    }else{
                        $receive_num[$g_t_d_v->custom_sku_id] = $g_t_d_v->receive_num;
                    }
                    // }else{
                    //     if(isset($receive_num[$g_t_d_v->custom_sku_id])){
                    //         $receive_num[$g_t_d_v->custom_sku_id]+=$g_t_d_v->transfers_num;
                    //     }else{
                    //         $receive_num[$g_t_d_v->custom_sku_id] = $g_t_d_v->transfers_num;
                    //     }
                    // }

                }



                // $v->goods_transfers_detail = $goods_transfers_detail;

                foreach ($num_info as $rk => $rv) {
                    # code...

                    $v_num = $rv??0;
                    $v_un_outnum =  $v_num;
                    $v_wait_outnum =0;
                    $v_receive_num = 0;
//                    $cus_s = db::table('self_custom_sku')->where('spu_id', $v->spu_id)->where('color',$v->color_identifying)->where('size',$rk)->first();
//                    if($cus_s){
                    $key2 = $v->spu_id.'-'.$v->color_identifying.'-'.$rk;
                    $cus_id = $customSkuList[$key2] ?? 0;
                    if ($cus_id){
                        if(isset($un_outnum[$cus_id])){
                            $v_un_outnum = $rv-$un_outnum[$cus_id] - $wait_outnum[$cus_id];
                        }
                        if(isset($wait_outnum[$cus_id])){
                            $v_wait_outnum = $wait_outnum[$cus_id];
                        }
                        if(isset($receive_num[$cus_id])){
                            $v_receive_num = $receive_num[$cus_id];
                        }

                        //出库数量 = 出库数量-退单数量
                        if(isset($gt_rt_detail[$cus_id])){
                            $v_receive_num -= $gt_rt_detail[$cus_id];
                        }

                      
                    }

                    $v_rk['num'] = $v_num;
                    $v_rk['v_un_outnum'] = $v_un_outnum < 0 ? 0 : $v_un_outnum;
                    $v_rk['v_wait_outnum'] = $v_wait_outnum;
                    $v_rk['v_receive_num'] = $v_receive_num;

                    $v->new[$rk] = $v_rk;
                    $v->$rk = $v_un_outnum;

                    $rule[$rk] = $rk;

                }
            }
            $orderId = explode(',', $v->order_id);
            $userName = [];
            $organizeName = [];
            foreach ($orderId as $o_id){
                $userId = $placeOrderMdl[$o_id] ?? 0;
                if (isset($userMdl[$userId])){
                    $userName[] = $userMdl[$userId];
                }
                if (isset($organizeMdl[$userId])){
                    $organizeName[] = $organizeMdl[$userId];
                }
            }
            $v->user_name = implode(',', array_unique($userName));
            $v->organize_name = implode(',', array_unique($organizeName));
            $v->img = $this->GetSpuColorImg($v->spu, $v->color_identifying);
        }

        $list = array_values(json_decode(json_encode($list),true));

        // $list = array_values($list->toArrayList());
        $rule = array_values($rule);
        $rulesb = [];
        foreach ($rule as $v) {
            # code...
            $sort = db::table('self_color_size')->where("identifying",$v)->first()->sort??0;
            $rulesb[] =  ['name'=>$v,'value'=>$v,'sort'=> $sort];
            $change[] =  ['name'=>$v,'value'=>$v,'sort'=> $sort];
        }

        usort($rulesb,function($a,$b){
            return $a['sort'] - $b['sort'];
        });


        $rules = array_merge($rules,$rulesb);

//        $list = $list->toArray();
//        $totalNum = count($list);
//        $list = array_slice($list, $page, $limit);


        $posttype = 1;
        if(isset($params['posttype'])){
            $posttype = $params['posttype'];
        }

        if($posttype==2){
            $p['title']='合同详情'.time();
            $p_title_list0 = [
                'contract_no'=>'合同号',
                'spu' => '款号',
                'title' => '品名',
                'img'=>'图片',
                'color_name'=>'中文颜色',
                'count'=>'数量'
            ];


            foreach ($change as $v) {
                # code...
                $p_title_list0[$v['name']] = $v['name'];
            }


            $p_title_list1 = [
                'color_identifying'=>'色号',
                'color_identifying'=>'英文颜色',
                'report_date'=>'交货期',
                'memo'=>'备注'
            ];


            $p['title_list'] = array_merge($p_title_list0,$p_title_list1);

            $p['data'] =   $list;
            $p['user_id'] =  $params['find_user_id']??1;  
            $p['type'] = '合同详情-导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;

            // return $p;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
        }

        return [
            'change'=>$change,
            'title'=>$rules,
            'data' => $list,
            'totalNum' => $totalNum,
        ];
    }

    
    //合同订单列表
    public function ContractListNew($params){

        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        // $where['status'] = 1;

        //类型1合同 2出库
        $where['a.type'] = 1;

        $list = Db::table('cloudhouse_contract as a')
            ->leftJoin('cloudhouse_contract_total as b', 'a.contract_no', '=', 'b.contract_no')
            ->where('a.status','!=',0);
        $allList = Db::table('cloudhouse_contract as a')
            ->leftJoin('cloudhouse_contract_total as b', 'a.contract_no', '=', 'b.contract_no')
            ->where('a.status','!=',0);

        if (isset($params['spu'])) {
            $query_spus = array();
            if (strstr($params['spu'], '，')) {
                $symbol = '，';
            } elseif (strstr($params['spu'], ',')) {
                $symbol = ',';
            } else {
                $symbol = '';
            }
            if ($symbol) {
                $spu_skuarray = explode($symbol,$params['spu']);
                foreach ($spu_skuarray as $key => $spu) {
                    $query_spus[] = $spu;
                }
                $spuMdl = db::table('self_spu')
                    ->where(function ($q) use ($query_spus) {
                        foreach ($query_spus as $spu){
                            $q->orwhere('spu', 'like', '%'.$spu.'%')
                                ->orwhere('old_spu', 'like', '%'.$spu.'%');
                        }
                        return $q;
                })
                    ->get(['id'])
                    ->toArrayList();
                $spuId = array_column($spuMdl, 'id');
                $list = $list->whereIn('a.spu_id',$spuId);
                $allList = $allList->whereIn('a.spu_id',$spuId);
            }else {
                $spuMdl = db::table('self_spu')
                    ->where('spu', 'like', '%'.$params['spu'].'%')
                    ->orwhere('old_spu', 'like', '%'.$params['spu'].'%')
                    ->get(['id'])
                    ->toArrayList();
                $spuId = array_column($spuMdl, 'id');
                $list = $list->whereIn('a.spu_id',$spuId);
                $allList = $allList->whereIn('a.spu_id',$spuId);
            }

        }


        if (isset($params['contract_no'])) {
            $query_c = array();
            if (strstr($params['contract_no'], '，')) {
                $symbol = '，';
            } elseif (strstr($params['contract_no'], ',')) {
                $symbol = ',';
            } else {
                $symbol = '';
            }
            if ($symbol) {
                $c_array = explode($symbol,$params['contract_no']);
                foreach ($c_array as $key => $c) {
                    $query_c[] = $c;
                }
                $list = $list->whereIn('a.contract_no',$query_c);
                $allList = $allList->whereIn('a.contract_no',$query_c);
            }else {
                $list = $list->where('a.contract_no','like','%'.$params['contract_no'].'%');
                $allList = $allList->where('a.contract_no','like','%'.$params['contract_no'].'%');
            }

        }

        if (isset($params['color'])) {
            $list = $list->whereIn('a.color_identifying',$params['color']);
            $allList = $allList->whereIn('a.color_identifying',$params['color']);
        }

        // if(isset($params['spu'])){
        //     $where['spu'] = $params['spu'];
        // }
        // if(isset($params['contract_no'])){
        //     $where['contract_no'] = $params['contract_no'];
        // }


        $list = $list->where($where);
        $allList = $allList->where($where);

        if(isset($params['start_time'])&&isset($params['end_time'])){
            $list = $list->whereBetween('a.report_date', [$params['start_time'], $params['end_time']]);
            $allList = $allList->whereBetween('a.report_date', [$params['start_time'], $params['end_time']]);
        }

        if (!isset($params['user_id']) || empty($params['user_id'])){
            if (isset($params['token']) && !empty($params['token'])){
                $users = db::table('users')->where('token',$params['token'])->first();
                $params['user_id'] = $users->Id ?? 0;
            }else{
                $params['user_id'] = 0;
            }
        }

        $controller = new Controller();
        $power = $controller->powers(['user_id' => $params['user_id'], 'identity' => ['show_all_contract_shipment']]);

        $totalNum = $list ->count();
        $list = $list
            ->offset($page)->limit($limit)
            ->select('a.id','a.spu','a.spu_id','b.memo','a.title','a.color_name','a.color_identifying',db::raw('sum(a.count) as count'),'a.one_price',db::raw('sum(a.price) as price'),'a.brand','a.report_date','a.contract_no','a.create_user','a.sign_date','a.num_info', 'a.order_id', 'b.contract_class')
            ->orderBy('a.create_time','desc')
            ->groupBy(['a.contract_no', 'a.spu_id', 'a.color_identifying'])
            ->get();
        $placeOrderMdl = db::table('amazon_place_order_task')
            ->get(['id', 'user_id'])
            ->pluck('user_id', 'id');
        $userMdl = db::table('users')
            ->get(['Id', 'account'])
            ->pluck('account', 'Id');
        $organizeMdl = db::table('organizes_member as a')
            ->leftJoin('organizes as b', 'a.organize_id', '=', 'b.Id')
            ->get(['a.user_id', 'b.name'])
            ->pluck('name', 'user_id');
        $allList = $allList
            ->select('a.contract_no', 'a.num_info', 'a.rule', 'a.spu_id', 'a.color_identifying', 'a.order_id')
            ->get();
        $allSizeList = [];
        foreach ($allList as $all){
            $key = $all->contract_no.'-'.$all->spu_id.'-'.$all->color_identifying;
            $num_info = json_decode($all->num_info, true);
            $rule = explode(',', $all->rule);
            if (isset($allSizeList[$key])){
                $allSizeList[$key]['rule'] = array_unique(array_merge($allSizeList[$key]['rule'], $rule));
                foreach ($rule as $r){
                    if (isset($allSizeList[$key]['num_info'][$r])){
                        $allSizeList[$key]['num_info'][$r] += $num_info[$r] ?? 0;
                    }else{
                        $allSizeList[$key]['num_info'][$r] = $num_info[$r] ?? 0;
                    }
                }
                $allSizeList[$key]['order_id'][] = $all->order_id;
            }else{
                $allSizeList[$key] = [
                    'num_info' => $num_info,
                    'rule' => $rule,
                    'order_id' => [$all->order_id],
                ];
            }
        }

        $rule = [];
        $rules = [];
        $change= [];

        $rules[0] = ['name'=>'id','value'=>'id','sort'=>0];
        $rules[1] = ['name'=>'合同号','value'=>'contract_no','sort'=>0];
        $rules[2] = ['name'=>'款号(SPU)','value'=>'spu','sort'=>0];
        $rules[3] = ['name'=>'下单颜色','value'=>'color_name','sort'=>0];
        $rules[4] = ['name'=>'颜色标识','value'=>'color_identifying','sort'=>0];
        $rules[5] = ['name'=>'交货期','value'=>'report_date','sort'=>0];
        $rules[6] = ['name'=>'品牌','value'=>'brand','sort'=>0];
        $rules[7] = ['name'=>'合同数量','value'=>'count','sort'=>0];
        $rules[8] = ['name'=>'单价(元)(含税)','value'=>'one_price','sort'=>0];
        $rules[9] = ['name'=>'金额(含税)','value'=>'price','sort'=>0];
        $rules[10] = ['name'=>'品名(中/英)','value'=>'title','sort'=>0];
        $rules[11] = ['name'=>'签约时间','value'=>'sign_date','sort'=>0];
        $rules[12] = ['name'=>'采购单号','value'=>'order_id','sort'=>0];
        $rules[13] = ['name'=>'部门','value'=>'organize_name','sort'=>0];
        $rules[14] = ['name'=>'备货人','value'=>'user_name','sort'=>0];

        $customSkuMdl = db::table('self_custom_sku')
            ->get(['id', 'color', 'size', 'spu_id']);
        $customSkuList = [];
        foreach ($customSkuMdl as $cus){
            $key = $cus->spu_id.'-'.$cus->color.'-'.$cus->size;
            $customSkuList[$key] = $cus->id;
        }
        $goods_transfers_detail_mdl = db::table('goods_transfers_detail as a')
            ->leftjoin('goods_transfers as b','a.order_no','=','b.order_no')
//            ->where('b.contract_no','like','%'.$v->contract_no.'%')
            ->whereIn('b.is_push',[1,2,3,4])
           ->where('b.type_detail', 2)
            ->get(['a.*', 'b.is_push']);



        $goods_transfers_detail_md2 = db::table('goods_transfers_detail as a')
        ->leftjoin('goods_transfers as b','a.order_no','=','b.order_no')
//            ->where('b.contract_no','like','%'.$v->contract_no.'%')
        ->whereIn('b.is_push',[1,2,3,4])
        ->where('b.type_detail', 9)
        ->get(['a.*', 'b.is_push']);
        $goodsTransfersDetailList = [];
        foreach ($goods_transfers_detail_mdl as $gd){
            $goodsTransfersDetailList[$gd->contract_no][] = $gd;
        }

        $goodsTransfersDetailListReturn = [];
        if($goods_transfers_detail_md2->isNotEmpty()){
            foreach ($goods_transfers_detail_md2 as $gd){
                $goodsTransfersDetailListReturn[$gd->contract_no][] = $gd;
            }
        }

        if (!isset($params['user_id']) || empty($params['user_id'])){
            if (isset($params['token']) && !empty($params['token'])){
                $users = db::table('users')->where('token',$params['token'])->first();
                if($users){
                    $params['user_id'] = $users->Id;
                }else{
                    $params['user_id'] = 0;
                }
            }else{
                $params['user_id'] = 0;
            }
        }

        foreach ($list as $k => $v) {
            if (!$power['show_all_contract_shipment'] && $v->contract_class != 3){
                if ($v->create_user != $params['user_id']){
                    unset($list[$k]);
                    continue;
                }
            }
            // $v->color_itf = $v->color_name.'/'.$v->color_identifying;
            $key = $v->contract_no.'-'.$v->spu_id.'-'.$v->color_identifying;
            if (isset($allSizeList[$key])){
                $v->num_info = json_encode($allSizeList[$key]['num_info']);
                $v->rule = implode(',', $allSizeList[$key]['rule']);
                $v->order_id = implode(',', array_unique($allSizeList[$key]['order_id']));
            }else{
                $v->num_info = '';
                $v->rule = '';
                $v->order_id = '';
            }
            $num_info = json_decode($v->num_info);
            if(!empty($num_info)){
//                $goods_transfers_detail = db::table('goods_transfers_detail as a')->leftjoin('goods_transfers as b','a.order_no','=','b.order_no')->where('b.contract_no','like','%'.$v->contract_no.'%')->whereIn('b.is_push',[1,2,3,4])->get();
                $goods_transfers_detail = $goodsTransfersDetailList[$v->contract_no] ?? [];

                $goods_transfers_detail_return = $goodsTransfersDetailListReturn[$v->contract_no] ?? [];

                $gt_rt_detail = [];

                if(!empty($goods_transfers_detail_return)){
                    foreach ($goods_transfers_detail_return as $gtrdv) {
                        # code...
                        if(isset($gt_rt_detail[$gtrdv->custom_sku_id])){
                            $gt_rt_detail[$gtrdv->custom_sku_id]+=$gtrdv->receive_num;
                        }else{
                            $gt_rt_detail[$gtrdv->custom_sku_id] = $gtrdv->receive_num;
                        }
    
                    }
                }

                //合同数量 
                // 未出货数量 goods_transfers_detail  合同数 - receive_num  状态未完成 = 合同数-transfers_num
                // 已出货待入库数量 transfers_num-receive_num
                // 已入库数量receive_num  type_detail = 2(出货)   - type_detail = 9（退货）
                $un_outnum = [];
                $wait_outnum = [];
                $receive_num = [];
                foreach ($goods_transfers_detail as $g_t_d_v) {
                    # code...
                    //已完成
                    // if($g_t_d_v->is_push==3){
                    if(isset($un_outnum[$g_t_d_v->custom_sku_id])){
                        $un_outnum[$g_t_d_v->custom_sku_id]+=$g_t_d_v->receive_num;
                    }else{
                        $un_outnum[$g_t_d_v->custom_sku_id] = $g_t_d_v->receive_num;
                    }
                    // }else{
                    //     if(isset($un_outnum[$g_t_d_v->custom_sku_id])){
                    //         $un_outnum[$g_t_d_v->custom_sku_id]+=$g_t_d_v->transfers_num;
                    //     }else{
                    //         $un_outnum[$g_t_d_v->custom_sku_id] = $g_t_d_v->transfers_num;
                    //     }
                    // }

                    if(isset($wait_outnum[$g_t_d_v->custom_sku_id])){
                        $wait_outnum[$g_t_d_v->custom_sku_id]+=$g_t_d_v->transfers_num-$g_t_d_v->receive_num;
                    }else{
                        $wait_outnum[$g_t_d_v->custom_sku_id] = $g_t_d_v->transfers_num-$g_t_d_v->receive_num;
                    }


                    // if($g_t_d_v->is_push==3){
                    if(isset($receive_num[$g_t_d_v->custom_sku_id])){
                        $receive_num[$g_t_d_v->custom_sku_id]+=$g_t_d_v->receive_num;
                    }else{
                        $receive_num[$g_t_d_v->custom_sku_id] = $g_t_d_v->receive_num;
                    }
                    // }else{
                    //     if(isset($receive_num[$g_t_d_v->custom_sku_id])){
                    //         $receive_num[$g_t_d_v->custom_sku_id]+=$g_t_d_v->transfers_num;
                    //     }else{
                    //         $receive_num[$g_t_d_v->custom_sku_id] = $g_t_d_v->transfers_num;
                    //     }
                    // }

                }



                // $v->goods_transfers_detail = $goods_transfers_detail;

                foreach ($num_info as $rk => $rv) {
                    # code...

                    $v_num = $rv??0;
                    $v_un_outnum =  $v_num;
                    $v_wait_outnum =0;
                    $v_receive_num = 0;
//                    $cus_s = db::table('self_custom_sku')->where('spu_id', $v->spu_id)->where('color',$v->color_identifying)->where('size',$rk)->first();
//                    if($cus_s){
                    $key2 = $v->spu_id.'-'.$v->color_identifying.'-'.$rk;
                    $cus_id = $customSkuList[$key2] ?? 0;
                    if ($cus_id){
                        if(isset($un_outnum[$cus_id])){
                            $v_un_outnum = $rv-$un_outnum[$cus_id] - $wait_outnum[$cus_id];
                        }
                        if(isset($wait_outnum[$cus_id])){
                            $v_wait_outnum = $wait_outnum[$cus_id];
                        }
                        if(isset($receive_num[$cus_id])){
                            $v_receive_num = $receive_num[$cus_id];
                        }

                        //出库数量 = 出库数量-退单数量
                        if(isset($gt_rt_detail[$cus_id])){
                            $v_receive_num -= $gt_rt_detail[$cus_id];
                        }

                      
                    }

                    $v_rk['num'] = $v_num;
                    $v_rk['v_un_outnum'] = $v_un_outnum < 0 ? 0 : $v_un_outnum;
                    $v_rk['v_wait_outnum'] = $v_wait_outnum;
                    $v_rk['v_receive_num'] = $v_receive_num;

                    $v->new[$rk] = $v_rk;
                    $v->$rk = $v_un_outnum;

                    $rule[$rk] = $rk;

                }
            }
            $orderId = explode(',', $v->order_id);
            $userName = [];
            $organizeName = [];
            foreach ($orderId as $o_id){
                $userId = $placeOrderMdl[$o_id] ?? 0;
                if (isset($userMdl[$userId])){
                    $userName[] = $userMdl[$userId];
                }
                if (isset($organizeMdl[$userId])){
                    $organizeName[] = $organizeMdl[$userId];
                }
            }
            $v->user_name = implode(',', array_unique($userName));
            $v->organize_name = implode(',', array_unique($organizeName));
            $v->img = $this->GetSpuColorImg($v->spu, $v->color_identifying);
        }

        $list = array_values(json_decode(json_encode($list),true));

        // $list = array_values($list->toArrayList());
        $rule = array_values($rule);
        $rulesb = [];
        foreach ($rule as $v) {
            # code...
            $sort = db::table('self_color_size')->where("identifying",$v)->first()->sort??0;
            $rulesb[] =  ['name'=>$v,'value'=>$v,'sort'=> $sort];
            $change[] =  ['name'=>$v,'value'=>$v,'sort'=> $sort];
        }

        usort($rulesb,function($a,$b){
            return $a['sort'] - $b['sort'];
        });


        $rules = array_merge($rules,$rulesb);

//        $list = $list->toArray();
//        $totalNum = count($list);
//        $list = array_slice($list, $page, $limit);


        $posttype = 1;
        if(isset($params['posttype'])){
            $posttype = $params['posttype'];
        }

        if($posttype==2){
            $p['title']='合同详情'.time();
            $p_title_list0 = [
                'contract_no'=>'合同号',
                'spu' => '款号',
                'title' => '品名',
                'img'=>'图片',
                'color_name'=>'中文颜色',
                'count'=>'数量'
            ];


            foreach ($change as $v) {
                # code...
                $p_title_list0[$v['name']] = $v['name'];
            }


            $p_title_list1 = [
                'color_identifying'=>'色号',
                'color_identifying'=>'英文颜色',
                'report_date'=>'交货期',
                'memo'=>'备注'
            ];


            $p['title_list'] = array_merge($p_title_list0,$p_title_list1);

            $p['data'] =   $list;
            $p['user_id'] =  $params['find_user_id']??1;  
            $p['type'] = '合同详情-导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;

            // return $p;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
        }

        return [
            'change'=>$change,
            'title'=>$rules,
            'data' => $list,
            'totalNum' => $totalNum,
        ];
    }


    // public function purchase_order_list($params){
    //     $list =  db::table('purchase_order_list')
    // }
     //出货
     public function ContractOutOld($params){

        Redis::Set('ContractOut',json_encode($params));
        return ['type'=>'success','msg'=>json_encode($params)];
        
        $detail = array();

        $out_no = rand(100,999).time();
        
        $house_type = $params['house_type']; //入库仓库  1同安仓 2泉州仓 3云仓 4.工厂虚拟仓 5.其它 6.工厂寄存仓 21工厂直发仓
        $box_num = isset($params['box_num'])?$params['box_num']:0;//箱数

        $skunum = 0;
        $goodsnum = 0;
        $time = date('Y-m-d H:i:s',time());
        db::beginTransaction();    //开启事务
        $sku_idArr = array();
        $change = $params['change'];
        foreach ($params['data'] as $one) {

            foreach ($change as $v) {
                # code...
                $size = $v['value'];
                $num = $one[$size]??0;
                if($num>0){

                    $insert['color_name'] = $one['color_name']??'';
                    $insert['color_identifying'] = $one['color_identifying']??'';

                    $GetSpuId = $this->GetSpuId($one['spu']);
                    if(!$GetSpuId){
                        return [
                            'type' => 'fail',
                            'msg' => '未获取到'.$one['spu'].'的spuId'
                        ];
                    }
                    $customsku = Db::table('cloudhouse_custom_sku')->where('contract_no',$one['contract_no'])->where('size',$size)->where('spu_id',$GetSpuId)->Where('color',$insert['color_identifying'])->first();

                    if(!$customsku){
                        db::rollback();// 回调
                        return [
                            'type' => 'fail',
                            'msg' => '非法出货，出货时无此数据,合同号：'.$one['contract_no'].'--spu:'.$one['spu'].'--size:'.$size.'--spuid='.$GetSpuId.'--color='.$insert['color_identifying']
                        ];
                    }else{
                        $sku_idArr[] = $customsku->custom_sku_id;
                        //sku个数
                        $skunum++;
                        // $detail[]= ['custom_sku'=> $customsku->custom_sku,'num'=>$num];
                        //订单号去重
                        $detail[$one['contract_no']] = 1;
                        //商品总数
                        $goodsnum += $num;

                        $getOld = $this->GetOldCustomSku($customsku->custom_sku);
                        if($getOld){
                            $detailinsert['custom_sku'] = $getOld;
                        }else{
                            $detailinsert['custom_sku'] = $customsku->custom_sku;
                        }

                        $detailinsert['custom_sku_id'] = $customsku->custom_sku_id;
                        $detailinsert['spu_id'] = $customsku->spu_id;
                        //调拨数量
                        $detailinsert['transfers_num'] = $num;

                        //实际数量
                        $factory_num = Db::table('self_custom_sku')->where('id',$customsku->custom_sku_id)->select('factory_num','is_cloud','custom_sku','old_custom_sku')->first();
                        if(empty($factory_num)){
                            db::rollback();// 回调
                            return [
                                'type' => 'fail',
                                'msg' => '没有找到此id--'.$customsku->custom_sku_id.'的数据'
                            ];
                        }
                        $factory_num = json_decode(json_encode($factory_num),true);

                        $receiveNum = Db::table('goods_transfers_detail as a')->leftJoin('goods_transfers as b','a.order_no','=','b.order_no')->where('a.custom_sku_id',
                            $customsku->custom_sku_id)->where('a.contract_no', $one['contract_no'])->where('b.type_detail',2)->sum('a.receive_num');



                        if($house_type==3){
                            if($factory_num['old_custom_sku']){
                                $thisSku = $factory_num['old_custom_sku'];
                            }else{
                                $thisSku = $factory_num['custom_sku'];
                            }
                            if($factory_num['is_cloud']==0){
                                $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
                                try {
                                    $cloud::sendJob([$thisSku]);
                                } catch(\Exception $e){
                                    Redis::Lpush('send_goods_fail',json_encode($thisSku));
                                }
                            }
                        }

                        $detailinsert['receive_num'] = 0;
                        $detailinsert['receive_time'] = $time;

                        }
                        //spu
                        $detailinsert['spu'] = $one['spu']??'';
                        //合同号
                        $detailinsert['contract_no'] = $one['contract_no']??'';
                        //批号
                        $detailinsert['order_no'] = $out_no;
                        //创建时间
                        $detailinsert['createtime'] =  $time;
                        //插入详情
                        Db::table('goods_transfers_detail')->insert($detailinsert);

                    }
                }
            
            }

        $uniqueArr = array_unique($sku_idArr);
        if(count($uniqueArr)!=count($sku_idArr)){
            return [
                'type' => 'fail',
                'msg' => '同一清单中不能出现sku一致的产品，请分两次推送'
            ];
        }


        //批号
        $transfersinsert['order_no'] = $out_no;
        //合同号
        $transfersinsert['contract_no'] = json_encode(array_keys($detail));

        $transfersinsert['img_url'] = isset($params['img_url'])?json_encode($params['img_url']):'';//图片
        $transfersinsert['file_url'] = isset($params['file_url'])?json_encode($params['file_url']):''??'';//附件

        $transfersinsert['createtime'] =  $time;
        //出库sku数量
        $transfersinsert['sku_count'] = $skunum;
        //出库数量
        $transfersinsert['total_num'] = $goodsnum;
        //实际数量
        $transfersinsert['receive_total_num'] = 0;
        //箱数
        $transfersinsert['box_num'] = $box_num;
        //平台
        $transfersinsert['platform_id'] = $params['platform_id']??'';
        //入库仓库
        $transfersinsert['in_house'] = $params['house_type']??'';
        //出仓仓库
        $transfersinsert['out_house'] = 4;
        //出库用户
        $transfersinsert['user_id'] = $params['user_id'];

        $transfersinsert['anomaly_order'] =  $params['anomaly_order']??'';
        $transfersinsert['text'] =  $params['text']??'';
        $transfersinsert['type'] = 1;

        $transfersinsert['is_qc'] = $params['is_qc'] ?? 0;

        if($house_type==1||$house_type==2||$house_type==3||$house_type==6||$house_type==21){
            $transfersinsert['type_detail'] = 2;
//            //预计交货时间
            $transfersinsert['yj_arrive_time'] =  $params['yj_arrive_time']??'2000-01-01 00:00:00';
//            //卸货方
            $transfersinsert['unload'] =  $params['unload']??0;
        }

//        if($house_type==4){
//            $transfersinsert['type_detail'] = 13;
//            $transfersinsert['yj_arrive_time'] = $time;
//            $transfersinsert['sj_arrive_time'] = $time;
//            $transfersinsert['out_house'] = 0;
//            $transfersinsert['type'] = 3;
//            $transfersinsert['is_push'] = 3;
//            $transfersinsert['receive_total_num'] = $goodsnum;
//        }

        Db::table('goods_transfers')->insert($transfersinsert);

        db::commit();

        return ['type'=>'success','msg'=>'出货成功'];
    }


    public function ContractOutb($params){

        $q_s = [];
        $q['house_type'] = $params['house_type']??1;
        $q['box_num'] = $params['box_num']??1;
        $q['img_url'] = $params['img_url']??'';
        $q['file_url'] = $params['file_url']??'';
        $q['user_id'] = $params['user_id']??1;
        $q['anomaly_order'] = $params['anomaly_order']??'';
        $q['text'] = $params['text']??'';
        $q['is_qc'] = $params['is_qc']??1;
        $q['yj_arrive_time'] = $params['yj_arrive_time']??'';
        $q['unload'] = $params['unload']??'';
        $q['is_qc'] = $params['is_qc']??1;

        $n_data = [];
        foreach ($params['data'] as  $dv) {
            # code...
            $num_arr = $dv['num_arr'];
            foreach ($num_arr as $v) {
                # code...
                if($v['num']>0){
                    $platform_id = $v['id'];
                    $n_one['custom_sku_id'] = $dv['custom_sku_id'];
                    $n_one['purchaseNumber'] = $dv['purchaseNumber'];
                    $n_one['num'] = $v['num'];    
                    $n_data[$platform_id][] =  $n_one;
                }

            }


        }


        $out_nos = [];
        foreach ($n_data as $pid => $ndv) {
            $qs = [];
            $qs = $q;
            $qs['platform_id'] =  $pid;
            $qs['data'] = $ndv;
            try {
                //code...
                $return =  $this->ContractOutb($qs);
                if($return['type']=='fail'){
                    return ['type'=>'fail','msg'=> $return['msg']];
                }
                $out_nos[] = $return['out_no'];
            } catch (\Throwable $th) {
                //throw $th;
                return ['type'=>'fail','msg'=> $th->getLine().$th->getMessage()];
            }
      
        }




        return ['type'=>'success','msg'=>'成功','data'=>$out_nos];

    }
    //出货
    public function ContractOut($params){

        // Redis::Set('ContractOut',json_encode($params));
        // return ['type'=>'success','msg'=>json_encode($params)];

        // $is_push =  db::table('goods_transfers')->whereIn('is_push',[2,4])->where('type_detail',2)->first();
        // if($is_push){
        //     return [
        //         'type' => 'fail',
        //         'msg' => '非法入库，已有采购单在进行，请完结后再入库'. $is_push->order_no
        //     ];
        // }
        
        $detail = array();

        $out_no = rand(100,999).time();
        
        $house_type = $params['house_type']; //入库仓库  1同安仓 2泉州仓 3云仓 4.工厂虚拟仓 5.其它 6.工厂寄存仓 21工厂直发仓
        $box_num = isset($params['box_num'])?$params['box_num']:0;//箱数

        $skunum = 0;
        $goodsnum = 0;
        $time = date('Y-m-d H:i:s',time());
        db::beginTransaction();    //开启事务
        $sku_idArr = array();

        // $change = $params['change'];
        foreach ($params['data'] as $v) {

                $num = $v['num'];
                if($num>0){
                // $customsku = Db::table('purchase_order_list')->where('purchaseNumber',$v['purchaseNumber'])->Where('custom_sku_id',$v['custom_sku_id'])->first();
                $customsku = Db::table('self_custom_sku')->Where('id',$v['custom_sku_id'])->first();
                if(!$customsku){
                    db::rollback();// 回调
                    return [
                        'type' => 'fail',
                        'msg' => '非法出货，无此采购单,单号：'.$v['purchaseNumber'].'--sku_id:'.$v['custom_sku_id']
                    ];
                }else{
                    $sku_idArr[] = $customsku->id;
                    //sku个数
                    $skunum++;
                    // $detail[]= ['custom_sku'=> $customsku->custom_sku,'num'=>$num];
                    //订单号去重
                    $detail[$v['purchaseNumber']] = 1;
                    //商品总数
                    $goodsnum += $num;

                    $getOld = $this->GetOldCustomSku($customsku->custom_sku);
                    if($getOld){
                        $detailinsert['custom_sku'] = $getOld;
                    }else{
                        $detailinsert['custom_sku'] = $customsku->custom_sku;
                    }

                    $detailinsert['custom_sku_id'] = $customsku->id;
                    $detailinsert['spu_id'] = $customsku->spu_id;
                    //调拨数量
                    $detailinsert['transfers_num'] = $num;

                    // //实际数量
                    // $factory_num = Db::table('self_custom_sku')->where('id',$customsku->custom_sku_id)->select('factory_num','is_cloud','custom_sku','old_custom_sku')->first();
                    // if(empty($factory_num)){
                    //     db::rollback();// 回调
                    //     return [
                    //         'type' => 'fail',
                    //         'msg' => '没有找到此id--'.$customsku->custom_sku_id.'的数据'
                    //     ];
                    // }
                    // $factory_num = json_decode(json_encode($factory_num),true);

                    // $receiveNum = Db::table('goods_transfers_detail as a')->leftJoin('goods_transfers as b','a.order_no','=','b.order_no')->where('a.custom_sku_id',
                    //     $customsku->custom_sku_id)->where('a.contract_no', $v['purchaseNumber'])->where('b.type_detail',2)->sum('a.receive_num');



                    // if($house_type==3){
                    //     if($factory_num['old_custom_sku']){
                    //         $thisSku = $factory_num['old_custom_sku'];
                    //     }else{
                    //         $thisSku = $factory_num['custom_sku'];
                    //     }
                    //     if($factory_num['is_cloud']==0){
                    //         $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
                    //         try {
                    //             $cloud::sendJob([$thisSku]);
                    //         } catch(\Exception $e){
                    //             Redis::Lpush('send_goods_fail',json_encode($thisSku));
                    //         }
                    //     }
                    // }

                    $detailinsert['receive_num'] = 0;
                    $detailinsert['receive_time'] = $time;

                    }
                    //spu
                    $detailinsert['spu'] = $v['spu']??'';
                    //合同号
                    $detailinsert['contract_no'] = $v['purchaseNumber']??'';
                    //批号
                    $detailinsert['order_no'] = $out_no;
                    //创建时间
                    $detailinsert['createtime'] =  $time;

                    $n_ratio = [];
                    $receive_num_arr = [];

                    $platform = db::table('platform')->get();

                    $rd_arr = [];
                    foreach ($platform as $pfv) {
                        # code...
                        $rd_arr[$pfv->Id] = 0;
                    }

                    // //根据比例  预分配数量
                    // $ratios = db::table('cloudhouse_custom_sku')->where('contract_no',$v['purchaseNumber'])->where('custom_sku_id',$customsku->id)->first();
                    // if($ratios){
                    //     $ratio = json_decode($ratios->ratio,true);
                    //     if(is_array($ratio)){
                    //         $r_all = 0;
                    //         foreach ($ratio as $rk => $rv) {
                    //             # code...
                    //             $r_all+=$rv;
                    //         }
                    //         $r_one = 0;
                    //         if($r_all>0){
                    //             $r_one =  $num/$r_all;
                    //         }

                    //         $receive_num_arr = [];
                    //         foreach ($ratio as $rk => $rv) {
                    //             # code...
                    //             $r_num = ceil($rv * $r_one);  `platform_id` int(11) DEFAULT '0',
                    //             if($r_num> $num){
                    //                 $r_num =  $num;
                    //             }
                    //             $num -=$r_num;

                    //             $n_ratio[$rk] = $r_num;
                    //             $receive_num_arr[$rk] = 0;
                    //         }

                    //     }
                    // }

                    $detailinsert['ratio_detail'] =  json_encode($rd_arr);
                    $detailinsert['receive_num_arr'] =  json_encode($receive_num_arr);

                    //插入详情
                    Db::table('goods_transfers_detail')->insert($detailinsert);

                }
                
            
            }

        $uniqueArr = array_unique($sku_idArr);
        if(count($uniqueArr)!=count($sku_idArr)){
            return [
                'type' => 'fail',
                'msg' => '同一清单中不能出现sku一致的产品，请分两次推送'
            ];
        }


        //批号
        $transfersinsert['order_no'] = $out_no;
        //合同号
        $transfersinsert['contract_no'] = json_encode(array_keys($detail));

        $transfersinsert['img_url'] = isset($params['img_url'])?json_encode($params['img_url']):'';//图片
        $transfersinsert['file_url'] = isset($params['file_url'])?json_encode($params['file_url']):''??'';//附件

        $transfersinsert['createtime'] =  $time;
        //出库sku数量
        $transfersinsert['sku_count'] = $skunum;
        //出库数量
        $transfersinsert['total_num'] = $goodsnum;
        //实际数量
        $transfersinsert['receive_total_num'] = 0;
        //箱数
        $transfersinsert['box_num'] = $box_num;
        //平台
        $transfersinsert['platform_id'] = 0;
        //入库仓库
        $transfersinsert['in_house'] = $params['house_type']??'';
        //出仓仓库
        $transfersinsert['out_house'] = 1;
        //出库用户
        $transfersinsert['user_id'] = $params['user_id'];

        $transfersinsert['anomaly_order'] =  $params['anomaly_order']??'';
        $transfersinsert['text'] =  $params['text']??'';
        $transfersinsert['type'] = 1;

        $transfersinsert['is_qc'] = $params['is_qc'] ?? 0;

        if($house_type==1||$house_type==2||$house_type==3||$house_type==6||$house_type==21){
            $transfersinsert['type_detail'] = 2;
//            //预计交货时间
            $transfersinsert['yj_arrive_time'] =  $params['yj_arrive_time']??'2000-01-01 00:00:00';
//            //卸货方
            $transfersinsert['unload'] =  $params['unload']??0;
        }

//        if($house_type==4){
//            $transfersinsert['type_detail'] = 13;
//            $transfersinsert['yj_arrive_time'] = $time;
//            $transfersinsert['sj_arrive_time'] = $time;
//            $transfersinsert['out_house'] = 0;
//            $transfersinsert['type'] = 3;
//            $transfersinsert['is_push'] = 3;
//            $transfersinsert['receive_total_num'] = $goodsnum;
//        }

        Db::table('goods_transfers')->insert($transfersinsert);

        db::commit();

        return ['type'=>'success','msg'=>'出货成功','data'=> [$out_no]];
    }

    public function SetPlanRatio($params){

        $id = $params['id'];
        $data = $params['data'];

        foreach ($data as $v) {
            # code...
            $ratio[$v['platform_id']] = $v['num'];
        }
        $ratio_detail = json_encode($ratio);
        db::table('goods_transfers_detail')->where('id',$id)->update(['ratio_detail'=>$ratio_detail]);

    }

    public function WaitInhouseList($params){
        // db::table('')
    }

    public function PushInhouse($params){
        $id = $params['id'];
        $order = Db::table('goods_transfers')->where('id',$id)->first();
        $order_detail =  Db::table('goods_transfers_detail')->where('order_no',$order->order_no)->get();

//        $detail = array();
        foreach ($order_detail as $k => $v) {
            # code...
//            $detail[]= ['custom_sku'=> $v->custom_sku,'num'=>$v->transfers_num];
            $custom_arr[] = $v->custom_sku;
        }
        $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
        try {
            $cloud::sendJob($custom_arr);
        } catch(\Exception $e){
            Redis::Lpush('send_goods_fail',$custom_arr);
        }
//                //云仓则加入队列
//        $quequeres['order_no'] = $order->order_no;
//        $quequeres['detail'] = $detail;
//        $quequeres['inhouse_type'] = 1;
//        return $quequeres;
        // $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
        // try {
        //     $cloud::inhouseJob($quequeres);
        // } catch(\Exception $e){
        //     Redis::Lpush('in_house_fail',json_encode($quequeres));
        // }

    }


    public function ContractSyncDetail($params)
    {
        $id = $params['id'];

        $one = DB::table('cloudhouse_contract')->where('id',$id)->limit(1)->get()->map(function($value){
            return(array)$value;
        })->toArray()[0];
        $customskus = array();
        $GetSpuId = $this->GetSpuId($one['spu']);
        if(!$GetSpuId){
            return [
                'type' => 'fail',
                'msg' => '未获取到'.$one->spud.'的spuId'
            ];
        }
        # code...
        $sizes = array();
        $sizes['XXS'] =  $one['XXS']??0;
        $sizes['XS'] =  $one['XS']??0;
        $sizes['S'] =  $one['S']??0;
        $sizes['M'] =  $one['M']??0;
        $sizes['L'] =  $one['L']??0;
        $sizes['XL'] = $one['XL']??0;
        $sizes['2XL'] =  $one['2XL']??0;
        $sizes['3XL'] =  $one['3XL']??0;
        $sizes['4XL'] =  $one['4XL']??0;
        $sizes['5XL'] =  $one['5XL']??0;
        $sizes['6XL'] =  $one['6XL']??0;
        $sizes['7XL'] =  $one['7XL']??0;
        $sizes['8XL'] = $one['8XL']??0;
        foreach ($sizes as $key => $num) {
            # code...
            if($num>0){
                $customsku = Db::table('cloudhouse_custom_sku')->where('contract_no',$one['contract_no'])->where('size',$key)->where('spu_id',$GetSpuId)->where('color',$one['color_identifying'])->first();
                if(!$customsku){
                    return [
                        'type' => 'fail',
                        'msg' => '非法同步，出库时无此数据,合同号：'.$one['contract_no'].'--spu:'.$one['spu'].'--size:'.$key
                    ];
                }else{
                    if($this->GetOldCustomSku($customsku->custom_sku)){
                        $customskus[]= $this->GetOldCustomSku($customsku->custom_sku);
                    }else{
                        $customskus[]= $customsku->custom_sku;
                    }

                }
            }
        }

        $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
        try {
            $cloud::sendJob($customskus);
        } catch(\Exception $e){
            Redis::Lpush('send_goods_fail',json_encode($params));
            return ['type'=>'fail','msg'=>'加入同步队列失败'];
        }

        return ['type'=>'success','msg'=>'加入同步队列成功'];
    }

    public function ContractOutlog($params)
    {
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        //类型1合同 2出库
        $where['type'] = 2;


        if(isset($params['out_no'])){
            $where['out_no'] = $params['out_no'];
        }

        $list = Db::table('cloudhouse_contract')->where($where);

        $totalNum = $list->groupBy('out_no')->count();
        $list = $list->offset($page)->limit($limit)->select('out_no','create_user','sign_date','create_time','is_push','status','house_type')->groupBy('out_no')->get()->map(function($value){
            return(array)$value;
        })->toArray();

        foreach ($list as &$v) {
            $v['create_user'] = $this->GetUsers($v['create_user'])['account'];

            if($v['is_push']==0){
                $v['state'] = '待取消';
            }
            if($v['is_push']==1){
                $v['state'] = '待推送';
            }
            if($v['is_push']==2){
                $v['state'] = '推送成功';
            }
            if($v['is_push']==3){
                $v['state'] = '取消成功';
            }
            if($v['is_push']==4){
                $v['state'] = '取消失败';
            }
            if($v['is_push']==5){
                $v['state'] = '云仓已入库';
            }
            //是否推送ispush 0取消推送1等待推送2成功3取消成功4取消失败5已入库
   
        }
        return [
            'data' => $list,
            'totalNum' => $totalNum,
        ];
    }

    //取消出库 
//    public function ContractCancel($params){
//        $out_no = $params['out_no'];
//
//        $outres = Db::table('cloudhouse_contract')->where('out_no', $out_no)->first();
//        if(!$outres ){
//            return ['type'=>'fail','msg'=>'无此出库订单，请检查出库号'];
//        }
//        //是否推送ispush 0取消推送1等待推送2成功3取消成功4取消失败5已入库
//        if($outres->is_push==0){
//            return ['type'=>'fail','msg'=>'已处于待取消状态，请耐心等待'];
//        }
//        if($outres->is_push==5){
//            return ['type'=>'fail','msg'=>'已入库，无法取消'];
//        }
//        if($outres->is_push==3){
//            return ['type'=>'fail','msg'=>'已取消成功，请勿重复推送'];
//        }
//
//        $now = time()-600;
//        $lasttime = $outres->create_time;
//        // if($now<strtotime($lasttime)){
//        //     return ['type'=>'fail','msg'=>'出库后，需要等待10分钟后才可以取消'];
//        // }
//        //取消推送
//        Db::table('cloudhouse_contract')->where('out_no', $out_no)->update(['is_push'=>0]);
//
//        //只有云仓需要加入队列
//        if($outres->house_type ==3){
//            $queueres['order_no'] = $out_no;
//            $queueres['order_type'] = 'in_house';
//            $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
//            try {
//                $cloud::cancelJob($queueres);
//            } catch(\Exception $e){
//                Redis::Lpush('order_cancel_fail',json_encode($queueres));
//            }
//        }
//
//        return ['type'=>'success','msg'=>'取消成功'];
//    }

    //取消出入库订单
    public function InhouseCancel($params){
        $in_no = $params['order_no'];

        $outres = Db::table('goods_transfers')->where('order_no', $in_no)->first();
        if(!$outres ){
            return ['type'=>'fail','msg'=>'无此调拨订单，请检查单号'];
        }
        if($outres->type_detail==12){
            $is_zfh = $params['is_zfh']??0;
            if($is_zfh==0){
                $fpx_order = DB::table('fpx_order')->where('out_no',$in_no)->select('id')->first();
                $lazada_order_item = DB::table('lazada_order_item')->where('out_no',$in_no)->select('id')->first();
                if(!empty($fpx_order)||!empty($lazada_order_item)){
                    return ['type'=>'fail','msg'=>'自发货订单请在自发货模块取消'];
                }
            }

        }
        db::beginTransaction();
        //是否推送ispush -2取消失败-1取消成功0推送失败1等待推送2成功3已确认
        if($outres->is_push==-2){
            return ['type'=>'fail','msg'=>'已处于取消状态'];
        }
        if($outres->is_push==3){
            return ['type'=>'fail','msg'=>'已确认，无法取消'];
        }
        if($outres->is_push==-1){
            return ['type'=>'fail','msg'=>'已取消成功，请勿重复推送'];
        }
        if($outres->is_push==4){
            $taskMdl = db::table('tasks')
                ->where('state', 3)
                ->where('ext', 'like', '%'.$params['order_no'].'%')
                ->where('class_id', 87)
                ->first();
            if (empty($taskMdl)){
                return ['type'=>'fail','msg'=>'取消失败，未发布出库撤销任务或者出库撤销任务审核未通过！'];
            }
        }
        //只有云仓需要加入队列
        if($outres->out_house ==3){
            $queueres['order_no'] = $in_no;
            $queueres['order_type'] = 'PTCK';
            $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
            try {
                $cloud::cancelJob($queueres);
            } catch(\Exception $e){
                Redis::Lpush('order_cancel_fail',json_encode($queueres));
                return ['type'=>'fail','msg'=>'取消失败'];
            }
        }
        if($outres->in_house ==3){
            if($outres->type_detail==2){
                $queueres['order_type'] = 'CGRK';
            }else{
                $queueres['order_type'] = 'DBRK';
            }
            $queueres['order_no'] = $in_no;

            $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
            try {
                $cloud::cancelJob($queueres);
            } catch(\Exception $e){
                Redis::Lpush('order_cancel_fail',json_encode($queueres));
                return ['type'=>'fail','msg'=>'取消失败'];
            }
        }


        $box_data = Db::table('goods_transfers_box as a')
            ->leftJoin('goods_transfers_box_detail as b','a.id','=','b.box_id')
            ->where('a.order_no',$in_no)
            ->select('b.custom_sku_id','b.box_num','b.shelf_num','b.location_ids','b.custom_sku','a.id')
            ->get();

        if(!$box_data->isEmpty()){
            $box_id = $box_data[0]->id;
        }
        //取消推送
        if($outres->out_house!=3&&$outres->in_house!=3) {
            Db::table('goods_transfers')->where('order_no', $in_no)->update(['is_push' => -1]);
            if(isset($box_id)){
                Db::table('goods_transfers_box')->where('id', $box_data[0]->id)->update(['is_delete' => 1]);
            }
        }
        $tasks = DB::table('tasks')->where('ext','like','%'.$in_no.'%')->select('Id')->first();
        if(!empty($tasks)){
            DB::table('tasks')->where('id',$tasks->Id)->update(['is_deleted'=>1]);
        }

        if( $outres->type_detail=25){
            db::table('goods_transfers_platform_log')->where('order_no',$in_no)->delete();
        }
        db::commit();// 确认
        return ['type'=>'success','msg'=>'取消成功'];
    }


    //查看出库订单
    public function ContractOutList($params){

        $out_no = $params['out_no'];
        $list = Db::table('cloudhouse_contract')->where('out_no',$out_no)->get()->map(function($value){
            return(array)$value;
        })->toArray();

        return ['type'=>'success','data'=>$list];
    }

    public function cloudhouse_custom_sku($params){
        $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
        try {
            $cloud::sendJob($params);
        } catch(\Exception $e){
            Redis::Lpush('send_goods_fail',json_encode($params));
        }
    }

    public function ContractTotalList($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $list = DB::table('cloudhouse_contract_total');
        //合同类型
        if(isset($params['contract_type'])){
            $list = $list->where('contract_type',$params['contract_type']);
        }
        if(isset($params['maker_id'])){
            $list = $list->where('maker_id',$params['maker_id']);
        }
        //公司抬头
        if(isset($params['company_name'])){
            $list = $list->where('company_name','like','%'.$params['company_name'].'%');
        }
        //供应商
        if(isset($params['supplier_name'])){
            $list = $list->where('supplier_short_name','like','%'.$params['supplier_name'].'%');
        }

        if(!empty($params['contract_no'])){
            $list = $list->where('contract_no','like','%'.$params['contract_no'].'%');
        }
        if(!empty($params['start_time'])){
            $list = $list->where('create_time','>',$params['start_time']);
        }
        if(!empty($params['end_time'])){
            $list = $list->where('create_time','<',$params['end_time']);
        }
        $totalData = $list->select('contract_no','total_count')->get();
        $totalNum = count($totalData);
        $list = $list->orderBy('create_time','desc')->offset($page)->limit($limit)->select()->get();

        $billMdl = db::table('financial_bill')
            ->whereIn('bill_type', [1,2])
            ->where('status', '<>', -3)
            ->get();
        $deductionMdl = db::table('financial_bill_deduction')
            ->where('is_deleted', 0)
            ->get();

        $billList = [];
        foreach ($billMdl as $b){
            if (isset($billList[$b->contract_no])){
                $billList[$b->contract_no] += $b->actual_payment;
            }else{
                $billList[$b->contract_no] = $b->actual_payment;
            }
        }
        foreach ($deductionMdl as $d){
            if (isset($billList[$d->contract_no])){
                $billList[$d->contract_no] += $d->deduction_amount;
            }else{
                $billList[$d->contract_no] = $d->deduction_amount;
            }
        }
        foreach ($list as $k=>$v){
            $list[$k]->out_num = DB::table('goods_transfers_detail as a')
                ->leftJoin('goods_transfers as b','a.order_no','=','b.order_no')
                ->where('b.type',1)
                ->where('a.contract_no',$v->contract_no)
                ->sum('a.receive_num');
//             DB::connection()->enableQueryLog();
            $production_num = DB::table('goods_transfers_detail as a')
                ->leftJoin('goods_transfers as b','a.order_no','=','b.order_no')
                ->where('b.type',3)
                ->where('a.contract_no',$v->contract_no)
                ->sum('a.receive_num');

            // 判断合同是否逾期
            $goodTransfers = DB::table('goods_transfers')
                ->where('contract_no', 'like', '%'.$v->contract_no.'%')
                ->where('type', 3)
                ->where('in_house', 4)
                ->where('out_house', 0)
                ->orderBy('createtime', 'ASC')
                ->first();
            $v->is_be_overdue = '';
            $timestamp = 0;
            $v->first_place_date = '';
            if (!empty($v->report_date)){
                if (!empty($goodTransfers)){
                    $v->first_place_date = $goodTransfers->sj_arrive_time;
                    $timestamp = strtotime($goodTransfers->sj_arrive_time) - strtotime($v->report_date);
                }else{
                    $v->first_place_date = '';
                    $timestamp = strtotime(date('Y-m-d H:i:s')) - strtotime($v->report_date);
                }
            }else{
                if (!empty($goodTransfers)){
                    $v->first_place_date = $goodTransfers->sj_arrive_time;
                }
            }

            if ($timestamp <0){
                $v->is_be_overdue = '未逾期';
                $v->be_overdue_time = '';
            }elseif($timestamp == 0){
                $v->is_be_overdue = '';
                $v->be_overdue_time = '';
            }else{
                $v->is_be_overdue = '已逾期';
                $v->be_overdue_time = $this->timestampConversion(abs($timestamp));
            }
            $v->maker_name = $this->GetUsers($v->maker_id)['account'] ?? '';
//             print_r(DB::getQueryLog());
            $list[$k]->surplus_num = $v->total_count - $v->out_num>0 ? $v->total_count - $v->out_num : 0;
//            $list[$k]->production_num = $production_num -  $v->out_num>0 ? $production_num - $v->out_num : 0;
            $list[$k]->production_num = $production_num;
            $pay_money = $billList[$v->contract_no] ?? 0;
            $not_pay_money = $v->total_price - $pay_money;
            $list[$k]->pay_money = $this->floorDecimal($pay_money);
            $list[$k]->not_pay_money = $this->floorDecimal($not_pay_money);
        }

        $posttype = 1;
        if(isset($params['posttype'])){
            $posttype = $params['posttype'];
        }

        if($posttype==2){
            $p['title']='合同列表'.time();
            $p['title_list'] = [
                'contract_no'=>'合同号',
                'total_count' => '合同合计数量',
                'total_price' => '合计金额',
                'spu_count'=>'spu数量',
                'out_num'=>'已出货',
                'surplus_num'=>'未出货',
                'maker_name'=>'经办人',
                'supplier_short_name'=>'供应商',
                'company_name'=>'公司抬头',
                'is_be_overdue'=>'是否逾期',
                'be_overdue_time'=>'逾期时间',
                'first_place_date'=>'首批入库日期',
                'report_date'=>'交货期',
                'sign_date'=>'签约日期',
                'create_time'=>'创建时间'
            ];

            $p['data'] =   $list;
            $p['user_id'] =  $params['find_user_id']??1;  
            $p['type'] = '合同列表-导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
        }
        return [
            'data' => $list,
            'totalNum' => $totalNum,
        ];
    }


    public function financeContract(){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $list = DB::table('goods_transfers as a')
            ->leftJoin('cloudhouse_contract_total as b','a.contract_no','=','b.contract_no')
            ->where('anomaly_order','')
            ->where('is_push',3);

        if(!empty($params['contract_no'])){
            $list = $list->where('contract_no','like','%'.$params['contract_no'].'%');
        }
        if(!empty($params['start_time'])){
            $list = $list->where('yj_arrive_time','>',$params['start_time']);
        }
        if(!empty($params['end_time'])){
            $list = $list->where('yj_arrive_time','<',$params['end_time']);
        }
    }

    //出入库记录
    //type_detail(1.仓库调拨入库 2.采购入库 3.手工入库 4.样品退回入库 5.订单退货入库 6.fba出库 7.仓库调拨出库 8.第三方仓出库 9.采购退货出库 10.样品调拨出库 11.手工出库 12.订单出库)
    public function inventoryInOut($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }
        $posttype = $params['posttype']??1;
        //出入库记录
        $list = DB::table('cloudhouse_record');
        if(!empty($params['contract_no'])){
            $order_nolist = DB::table('goods_transfers as a')->leftJoin('goods_transfers_detail as b','a.order_no','=','b.order_no')
                ->where('b.contract_no','like','%'.$params['contract_no'].'%')->select('a.order_no','b.custom_sku_id')->get();
            $order_nolist = json_decode(json_encode($order_nolist),true);
            $order_noArr = array_column($order_nolist,'order_no');
            $skuArr = array_column($order_nolist,'custom_sku_id');
            $list = $list->whereIn('order_no',$order_noArr)->whereIn('custom_sku_id',$skuArr);
        }
        if(!empty($params['jg_contract_no'])){
            $contract_total = DB::table('cloudhouse_contract_total')->where('process_contract_no','like','%'.$params['jg_contract_no'].'%')
                ->select('contract_no')->get()->toArray();
            $contract_no_list = array_column($contract_total,'contract_no');
            $order_nolist = DB::table('goods_transfers as a')->leftJoin('goods_transfers_detail as b','a.order_no','=','b.order_no')
                ->whereIn('b.contract_no',$contract_no_list)->select('a.order_no','b.custom_sku_id')->get();
            $order_nolist = json_decode(json_encode($order_nolist),true);
            $order_noArr = array_column($order_nolist,'order_no');
            $skuArr = array_column($order_nolist,'custom_sku_id');
            $list = $list->whereIn('order_no',$order_noArr)->whereIn('custom_sku_id',$skuArr);
        }
        if(!empty($params['warehouse_id'])){
            $list = $list->where('warehouse_id',$params['warehouse_id']);
        }
        if(!empty($params['type'])){
            $list = $list->where('type',$params['type']);
        }
        if(!empty($params['user_id'])){
            $list = $list->where('user_id',$params['user_id']);
        }
        if(!empty($params['type_detail'])){
            $list = $list->where('type_detail',$params['type_detail']);
        }
        if(!empty($params['shop_id'])){
            $list = $list->where('shop_id',$params['shop_id']);
        }
        if(!empty($params['spu'])){
            $spuid = $this->GetSpuId($params['spu']);
            $list = $list->where('spu_id',$spuid);
        }
        if(!empty($params['custom_sku_name'])){
            $customSkuMdl = db::table('self_custom_sku')
                ->where('name', 'like', '%'.$params['custom_sku_name'].'%')
                ->get(['id'])
                ->toArrayList();
            $custom_sku_id = array_column($customSkuMdl, 'id');
            $list = $list->whereIn('custom_sku_id',$custom_sku_id);
        }
        if(!empty($params['order_no'])){
            $list = $list->where('order_no',$params['order_no']);
        }
        if(!empty($params['custom_sku'])){
            $custom_sku_id = $this->GetCustomSkuId($params['custom_sku']);
            $list = $list->where('custom_sku_id',$custom_sku_id);
        }
        if(!empty($params['platform_id'])){
            $order_nolist2 = DB::table('goods_transfers as a')->leftJoin('goods_transfers_detail as b','a.order_no','=','b.order_no')
                ->where('a.platform_id',$params['platform_id'])->select('a.order_no','b.custom_sku_id')->get();
            $order_nolist2 = json_decode(json_encode($order_nolist2),true);
            $order_noArr2 = array_column($order_nolist2,'order_no');
            $skuArr2 = array_column($order_nolist2,'custom_sku_id');
            $list = $list->whereIn('order_no',$order_noArr2)->whereIn('custom_sku_id',$skuArr2);
        }

        if($posttype==2){
            if(empty($params['start_time'])){
                $params['start_time'] = date('Y-m-d 00:00:00',time());
            }
            if(empty($params['end_time'])){
                $params['end_time'] = date('Y-m-d 23:59:59',time());
            }
        }
        if(!empty($params['start_time'])){
            $list = $list->where('createtime','>',$params['start_time']);
        }
        if(!empty($params['end_time'])){
            $list = $list->where('createtime','<',$params['end_time'].' 23:59:59');
        }
        $totalNum = $list->count();
        if($posttype==2){
            $list = $list->orderBy('id','desc')->get();
        }else{
            $list = $list->offset($page)->limit($limit)->orderBy('id','desc')->get();
        }

        $platform =  DB::table('platform')->select('Id','name')->get();
        $platformArr = [];
        foreach ($platform as $p){
            $platformArr[$p->Id] = $p->name;
        }

        $transfers = DB::table('goods_transfers_detail')
            ->select('receive_num','contract_no','custom_sku_id', 'order_no')
            ->get();
        $transfersDetail = [];
        foreach ($transfers as $v){
            $transfersDetail[$v->order_no][] = [
                'receive_num' => $v->receive_num,
                'contract_no' => $v->contract_no,
                'custom_sku_id' => $v->custom_sku_id
            ];
        }

        $contract_data = DB::table('cloudhouse_contract_total')
            ->select('supplier_short_name', 'contract_no', 'contract_class', 'process_supplier_name','process_contract_no')
            ->get()
            ->keyBy('contract_no');

        $goods = DB::table('amazon_create_goods')
            ->select('serial_no', 'request_id')
            ->get()
            ->keyBy('request_id');

        $goods_transfers = DB::table('goods_transfers')
            ->select('update_cause', 'order_no', 'platform_id','text', 'push_time', 'createtime')
            ->get()
            ->keyBy('order_no');
        foreach ($list as $k=>$v){
            $v->jg_contract_no = '';
            $v->contract_no = '';
           $v->shop_name = '';
           $v->cn_name = $this->GetCustomSkus($v->custom_sku)['name']??'';
           $v->platform = '';
           $v->serial_no = '';
           $v->update_cause = '';
           $v->supplier = '';
           $v->user_name = $this->GetUsers($v->user_id)['account']??'';
           $v->ys_user = $this->GetUsers($v->ys_user_id)['account']??'';
            if(isset($transfersDetail[$v->order_no])) {
//                $total_price = 0;
                foreach ($transfersDetail[$v->order_no] as $t) {
                    if($t['custom_sku_id']==$v->custom_sku_id){
                        $v->contract_no = $t['contract_no'];
                    }
                }
                $v->contract_no_price = round($v->price*$v->num,2);
            }

            if(isset($goods_transfers[$v->order_no])){
                $v->remark = $goods_transfers[$v->order_no]->text;
                if($v->type_detail==3||$v->type_detail==11){
                    $v->update_cause = $goods_transfers[$v->order_no]->update_cause;
                }
                $v->delivery_time = $goods_transfers[$v->order_no]->push_time ?? '';
                $v->input_time = $goods_transfers[$v->order_no]->createtime ?? '';
            }

           if($v->type_detail==2||$v->type_detail==9||$v->type_detail==13||$v->type_detail==14){
                    if(isset($contract_data[$list[$k]->contract_no])){
                        $process_supplier_name = '';
                        if ($contract_data[$list[$k]->contract_no]->contract_class == 5){
                            $process_supplier_name = '(加工厂：'.$contract_data[$list[$k]->contract_no]->process_supplier_name.')';
                        }
                       $v->supplier = $contract_data[$list[$k]->contract_no]->supplier_short_name.$process_supplier_name;
                        $v->jg_contract_no = $contract_data[$list[$k]->contract_no]->process_contract_no;
                    }
           }

            if($v->type_detail==6){
                if(isset($goods[$v->order_no])){
                   $v->serial_no = $goods[$v->order_no]->serial_no;
                }
            }

            if($v->shop_id){
                $getShop = $this->GetShop($v->shop_id);
                if($getShop){
                    if(isset($platformArr[$getShop['platform_id']])){
                       $v->platform = $platformArr[$getShop['platform_id']];
                    }
                   $v->shop_name = $getShop['shop_name'];
                }
            }else{
                if(isset($goods_transfers[$v->order_no])){
                    if($goods_transfers[$v->order_no]->platform_id){
                        $v->platform = $platformArr[$goods_transfers[$v->order_no]->platform_id];
                    }
                }
            }

            
            $v->type_detail_name = '';
            $v->type_house = '';
            if($v->warehouse_id==1){$v->warehouse = '同安仓';}
            if($v->warehouse_id==2){$v->warehouse = '泉州仓';}
            if($v->warehouse_id==3){$v->warehouse = '云仓';}
            if($v->warehouse_id==4){$v->warehouse = '工厂虚拟仓';}
            if($v->warehouse_id==5){$v->warehouse = '其它';}

            if($v->type==1){$v->type_house = '出库';}
            if($v->type==2){$v->type_house = '入库';}
            if($v->type_detail==1){$v->type_detail_name = '仓库调拨入库';}
            if($v->type_detail==2){$v->type_detail_name = '采购入库';}
            if($v->type_detail==3){$v->type_detail_name = '手工入库';}
            if($v->type_detail==4){$v->type_detail_name = '样品退回入库';}
            if($v->type_detail==5){$v->type_detail_name = '订单退货入库';}
            if($v->type_detail==6){$v->type_detail_name = 'fba出库';}
            if($v->type_detail==7){$v->type_detail_name = '仓库调拨出库';}
            if($v->type_detail==8){$v->type_detail_name = '第三方仓出库';}
            if($v->type_detail==9){$v->type_detail_name = '采购退货出库';}
            if($v->type_detail==10){$v->type_detail_name = '样品调拨出库';}
            if($v->type_detail==11){$v->type_detail_name = '手工出库';}
            if($v->type_detail==12){$v->type_detail_name = '订单出库';}
            if($v->type_detail==13){$v->type_detail_name = '工厂虚拟入库';}
            if($v->type_detail==14){$v->type_detail_name = '工厂虚拟出库';}
            if($v->type_detail==17){$v->type_detail_name = '组货出库';}
            if($v->type_detail==18){$v->type_detail_name = '组货入库';}

            $v->update_cause_name = '';
            if($v->update_cause==1){$v->update_cause_name = '错色';}
            if($v->update_cause==2){$v->update_cause_name = '错码';}
            if($v->update_cause==3){$v->update_cause_name = '错款';}
            if($v->update_cause==5){$v->update_cause_name = '盘点出库';}
            if($v->update_cause==4){$v->update_cause_name = '盘点入库';}
        }


   
        if($posttype==2){
            $ps['title']='出入库记录'.time();
            $ps['title_list'] = [
                'warehouse'=>'仓库',
                'type_house' => '出/入库',
                'type_detail_name' => '出入库类型',
                'platform'=>'国家',
                'cn_name'=>'商品名称',
                'contract_no'=>'采购单号',
                'order_no'=>'批号',
                'spu'=>'spu',
                'custom_sku'=>'库存sku',
                'num'=>'数量',
                'now_total_price'=>'仓库结余资产',
                'now_inventory'=>'结余库存',
                'user_name'=>'经办人',
                'update_cause_name'=>'手工出库调整原因',      
                'delivery_time' => '到货时间',
                'input_time' => '录入时间',
                'remark'=>'备注',
                'createtime'=>'时间'
            ];

            $ps['data'] =   $list;
            $ps['user_id'] =  $params['find_user_id']??1;  
            $ps['type'] = '出入库记录-导出';


            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($ps);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
        }
        return [
            'data' => $list,
            'totalNum' => $totalNum,
        ];

    }

    /**
     * @Desc:获取合同出货列表
     * @param $params
     * @return array
     * @author: Liu Sinian
     * @Time: 2023/3/1 16:32
     */
    public function getContractShipmentList($params)
    {
        $result = $this->_filterContractShipmentList($params);

        return $result;
    }

    /**
     * @Desc:获取合同出货列表
     * @param $params
     * @return array
     * @author: Liu Sinian
     * @Time: 2023/3/1 16:32
     */
    public function _filterContractShipmentList($params)
    {
        $goodsTransfersDetail = db::table('goods_transfers_detail as a')
            ->leftJoin('goods_transfers as b', 'a.order_no', '=', 'b.order_no')
            ->where('b.type_detail', 2);
        // 过滤预计送达时间
        if (isset($params['estimated_delivery_time']) && !empty($params['estimated_delivery_time'])){
            $goodsTransfersDetail->whereBetween('b.yj_arrive_time', $params['estimated_delivery_time'] ?? []);
        }
        // 实际送达时间
        if (isset($params['actual_delivery_time']) && !empty($params['actual_delivery_time'])){
            $goodsTransfersDetail->whereBetween('b.sj_arrive_time', $params['actual_delivery_time'] ?? []);
        }
        // 合同号
        if (isset($params['contract_no']) && !empty($params['contract_no'])){
            $goodsTransfersDetail->where('a.contract_no', 'like', '%' . $params['contract_no'] . '%');
        }
        // 品名
        if (isset($params['product_name']) && !empty($params['product_name'])){
            $customMdl = db::table('self_custom_sku')
                ->where('name', '%'.$params['product_name'].'%')
                ->get();
            $customSkuIds = [];
            if ($customMdl->isNotEmpty()){
                $customMdl = $customMdl->toArrayList();
                $customSkuIds = array_column($customMdl, 'id');
            }
            $goodsTransfersDetail->whereIn('a.custom_sku_id', $customSkuIds);
        }
        // 款号
        if (isset($params['spu']) && !empty($params['spu'])){
            $goodsTransfersDetail->where('a.spu', 'like', '%'.$params['spu'].'%');
        }
        // 入库数量
        if (isset($params['instock_num']) && !empty($params['instock_num'])) {
            $goodsTransfersDetail->where('a.receive_num', $params['instock_num']);
        }
        // 入库总数量
        if (isset($params['instock_total_num']) && !empty($params['instock_total_num'])) {
            $goodsTransfersDetail->where('b.receive_total_num', $params['instock_total_num']);
        }
        // 合同单价
        if (isset($params['one_price']) && !empty($params['one_price'])) {
            $spuIds = $this->contractModel::query()
                ->where('one_price', $params['one_price'])
                ->where('spu_id', '>', 0)
                ->select('spu_id')
                ->get();
            if (!empty($spuIds)){
                $spuIds = array_column($spuIds->toArray(), 'spu_id');
            }else{
                $spuIds = [];
            }
            $goodsTransfersDetail->whereIn('a.spu_id', $spuIds);
        }
//        // 合同数量
//        if (isset($params['contract_num']) && !empty($params['contract_num'])) {
//            $goodsTransfersDetail->where('cc.count', $params['contract_num']);
//        }
        // 备注
        if (isset($params['remark']) && !empty($params['remark'])){
            $goodsTransfersDetail->where('b.text', 'like', '%'.$params['remark'].'%');
        }
        // 过滤id
        if (isset($params['id']) && !empty($params['id'])) {
            $goodsTransfersDetail->whereIn('a.id', $params['id']);
        }
        // 仓库名称过滤
        if (isset($params['warehouse']) && !empty($params['warehouse'])){
            $goodsTransfersDetail->where('b.in_house', $params['warehouse']);
        }
        $count = $goodsTransfersDetail->count();
        // 排序
        $goodsTransfersDetail->orderBy('b.sj_arrive_time', 'desc');
        // 分页
        if (isset($params['limit']) && !empty($params['limit']) && isset($params['page']) && !empty($params['page'])) {
            $limit = $params['limit'] ?? 30;
            $page = $params['page'] ?? 1;
            $pageNum = $page <=1 ? 0 : $limit*($page-1);
            $goodsTransfersDetail->limit($limit)->offset($pageNum);
        }
        $goodsTransfersDetailList = $goodsTransfersDetail
            ->select('b.*', 'a.*')
            ->get()
            ->toArrayList();

//        $customMdl = $this->customSkuModel::query()
//            ->get();
        // 获取合同数据
        $contractCustomSkuMdl = db::table('cloudhouse_custom_sku')->get();
        $contractCustomSku = [];
        foreach ($contractCustomSkuMdl as $v){
            $key = $v->contract_no .'-'. $v->custom_sku_id;
            $contractCustomSku[$key] = $v;
        }
        $list = [];
        foreach ($goodsTransfersDetailList as $item){
            // 获取合同库存sku合同数量
//            $contactCustomSkuModel = db::table('')
//                ->where('contract_no', $item['contract_no'])
//                ->where('custom_sku_id', $item['custom_sku_id'])
//                ->first();
//            if (!empty($contactCustomSkuModel)){
//                $contactModel = $this->contractModel::query()
//                    ->where('contract_no', $contactCustomSkuModel->contract_no)
//                    ->where('spu_id', $contactCustomSkuModel->spu_id)
//                    ->where('color_identifying', $contactCustomSkuModel->color)
//                    ->first();
//            }
//            $color = '';
//            $size = '';
            $customMdl = $this->GetCustomSkus($item['custom_sku']);
            $colorMdl = $this->GetColorSize($customMdl['color_id']);
            $color = $colorMdl['name'] ?? '';
            $size = $customMdl['size'] ?? '';
//            foreach ($customMdl as $cu){
//                if ($cu->custom_sku_id == $item['custom_sku_id'] || $cu->custom_sku == $item['custom_sku'] || $cu->old_custom_sku == $item['custom_sku']){
//                    $colorMdl = $this->GetColorSize($cu->color_id);
//                    $color = $colorMdl['name'] ?? '';
//                    $size = $cu->size;
//                    break;
//                }
//            }
            $key = $item['contract_no'].'-'.$item['custom_sku_id'];
            $onePrice = 0;
            $contactNum = 0;
            if (isset($contractCustomSku[$key])){
                $onePrice = $contractCustomSku[$key]->price;
                $contactNum = $contractCustomSku[$key]->num;
            }
            $list[] = [
                'id' => $item['id'], // 标识
                'contract_no' => $item['contract_no'], // 合同号
                'spu' => $item['spu'], // 款号
                'custom_sku' => $item['custom_sku'], // 库存SKU
                'yj_arrive_time' => $item['yj_arrive_time'], // 送货时间
                'sj_arrive_time' => $item['sj_arrive_time'], // 实际入库时间
                'receive_num' => $item['receive_num'], // 实际入库数量
                'spu_id' => $item['spu_id'],
                'custom_sku_id' => $item['custom_sku_id'],
                'title' => $customMdl['name'] ?? '', // 品名
                'text' => $item['text'] ?? '', // 备注
//                'total_num' => $item['total_num'],
                'receive_total_num' => $item['receive_total_num'], // 实际入库总数
                'one_price' => $onePrice, // 单价
                'count' => $contactNum, // 数量
                'price' => $onePrice * $contactNum, // 合计价格
                'plant_code' => '', // 工厂代号,
                'warehouse_name' => self::WAREHOUSE[$item['in_house']] ?? '', // 仓库名称
                'color' => $color,
                'size' => $size
            ];
        }

        return ['count' => $count, 'list' => $list];
    }
    public function exportContractShipmentList($params)
    {
//        $goodsTransfersDetail = $this->goodsTransfersDetailModel::query()
//            ->join('goods_transfers as gt', 'gt.order_no', '=', 'goods_transfers_detail.order_no')
//            ->where('gt.type', 1);
//        // 过滤id
//        if (isset($params['id']) && !empty($params['id'])) {
//            $goodsTransfersDetail->whereIn('goods_transfers_detail.id', $params['id']);
//        }
//        $goodsTransfersDetailList = $goodsTransfersDetail
//            ->select('gt.*', 'goods_transfers_detail.*')
//            ->get()
//            ->toArray();
//        $list = [];
//        foreach ($goodsTransfersDetailList as $item){
//            // 获取合同库存sku合同数量
//            $contactCustomSkuModel = $this->contractSkuModel::query()
//                ->where('contract_no', $item['contract_no'])
//                ->where('custom_sku_id', $item['custom_sku_id'])
//                ->first();
//            if (!empty($contactCustomSkuModel)){
//                $contactModel = $this->contractModel::query()
//                    ->where('contract_no', $contactCustomSkuModel->contract_no)
//                    ->where('spu_id', $contactCustomSkuModel->spu_id)
//                    ->where('color_identifying', $contactCustomSkuModel->color)
//                    ->first();
//            }
//            $onePrice = $contactModel->one_price ?? 0;
//            $contactNum = $contactCustomSkuModel->num ?? 0;
//            $list[] = [
//                'id' => $item['id'], // 标识
//                'contract_no' => $item['contract_no'], // 合同号
//                'spu' => $item['spu'], // 款号
//                'custom_sku' => $item['custom_sku'], // 库存SKU
//                'yj_arrive_time' => $item['yj_arrive_time'], // 送货时间
//                'sj_arrive_time' => $item['sj_arrive_time'], // 实际入库时间
//                'receive_num' => $item['receive_num'], // 实际入库数量
//                'spu_id' => $item['spu_id'],
//                'custom_sku_id' => $item['custom_sku_id'],
//                'title' => $contactModel->title ?? '', // 品名
//                'text' => $item['text'] ?? '', // 备注
//                'receive_total_num' => $item['receive_total_num'], // 实际入库总数
//                'one_price' => $onePrice ? $onePrice : '', // 单价
//                'count' => $contactNum ? $contactNum : '', // 数量
//                'price' => $onePrice * $contactNum, // 合计价格
//                'plant_code' => '', // 工厂代号
//                'warehouse_name' => self::WAREHOUSE[$item['in_house']] ?? '' // 入库仓库
//            ];
//        }
        $data = $this->getContractShipmentList($params);
        $list = $data['list'];
        // excel文件表头
        $excelName = '合同出货列表导出'.time();
        // 表头
        $excelTitle = [
            'yj_arrive_time' => '送货日期',
            'sj_arrive_time' => '实际到货日期',
            'warehouse_name' => '入库仓库',
            'plant_code' => '工厂代号',
            'contract_no' => '合同号',
            'title' => '品名',
            'spu' => '款号',
            'color' => '颜色',
            'size' => '尺码',
            'receive_num' => '入库数量',
            'one_price' => '合同单价',
//            'receive_total_num' => '入库总额',
            'count' => '合同数量',
            'price' => '合同总额',
            'text' => '备注',
        ];
        // 组织导出列表数据
        $excelData = [
            'data' => $list,
            'title_list' => $excelTitle,
            'title' => $excelName,
            'type' => '合同出货列表导出',
            'user_id' => $params['export_user_id']
        ];

        return $excelData;
    }




    public function ConcactToOneDog($params){

        $contract_no = $params['contract_no'];

        $xmly_key = time().rand(10000,99999);
        $list = db::table('cloudhouse_contract')->where('contract_no',$contract_no)->select('title','img','count','one_price','report_date','rule','color_name','spu')->get();

        $shop_id = db::table('cloudhouse_custom_sku')->where('contract_no',$contract_no)->first()->shop_id??0;

        $t = db::table('cloudhouse_contract_total')->where('contract_no',$contract_no)->select('id','supplier_short_name','qc_user_id','file','input_user_id','maker_id','supplier_no','sign_date','report_date as all_report_date','periodic_id','create_time','memo','delivery_memo','contract_no','contract_class')->first();

        if(!$t){
            return '无此合同';
        }
        $payment_method = 1;
        if($t->periodic_id==0){$payment_method=1;}
        if($t->periodic_id==1||$t->periodic_id==2||$t->periodic_id==3){$payment_method=4;}
        if($t->periodic_id==4||$t->periodic_id==5){$payment_method=5;}

        $users = json_decode($this->GetOneDogUserId($t->input_user_id),true);
        $user = 0;
        if($users['code']==200){
            if(isset($users['data'][0]['id'])){
                $user = $users['data'][0]['id'];
            }
           
        }

        $gd_users = json_decode($this->GetOneDogUserId($t->maker_id),true);
        $gd_user = 0;
        if($gd_users['code']==200){
            if(isset($gd_users['data'][0]['id'])){
                $gd_user = $gd_users['data'][0]['id'];
            }
    
        }


        $suppliers = json_decode($this->GetOneDogSupplierId($t->supplier_no),true);
        $supplier = 0;
        if($suppliers['code']==200){
            $supplier = $suppliers['data']['id'];
        }
        $order_no = $contract_no;
        $shop_id = $shop_id;
        $data = [];
        $i = 0;
        $bi = 1;
        foreach ($list as $v) {
            # code...

            $one['goods_name'] = $v->title;//商品名称
            $one['lidan_url'] = $t->file??'';//商品名称
            $one['style_no'] = $v->spu;//订单号
            $one['order_no'] = $order_no;//订单号
            $one['user_yw'] = $user;//业务员
            $one['user_gd'] = $gd_user;//跟单员
            // $one['user_qc'] = 0;//QC员
            $one['img'] = $v->img??'';//商品图片
            $one['number'] = $v->count;//产品数量
            $one['unit'] = '';//数量单位
            $one['fabric'] = '';//面料成分
            $one['user_qc_name']  =$this->GetUsers($t->qc_user_id)['account']??'';

            $one['factory_name']  = $t->supplier_short_name??'';
            
            
            // $one['factory_id'] =  $supplier;//下单工厂id（factorys工厂表id）
            $one['price_gc'] = 0;//工厂单价（RMB）
            $one['price_sj'] = 0;//实际单价（USD)
            $one['money_pi'] = '';//PI总金额（USD
            $one['customs_unit'] = '';//报关单位
            $one['goods_time'] = $v->report_date??'';//工厂货期
            $one['nature'] = '';//订单性质：0卖单 1采购单
            $one['receiving_time'] = $t->sign_date??'';//接单日期
            $one['delivery_time'] = $t->all_report_date??'';//客户交期
            $one['product_category'] = 6;//产品类别：1.羽绒服；2.棉服/夹克/风衣；3.运动针织；4.沙滩裙；5.面料；6.其它

            $one['payment_method'] = $payment_method;//付款方式：1.100%；2.后TT/ LC；3.即期 /LC；4.30天  5.60天 / TT；6. 30/70 /TT；7.20/80'
            $one['order_time'] = $t->create_time;//下单时间

            $style = 2;
            $base_spu_id = $this->GetBaseSpuIdBySpu($v->spu);
            $base_spu = db::table('self_base_spu')->where('id',$base_spu_id)->first();
            if($base_spu){
                if($base_spu->seasonal_style==1){
                    $style=2;
                }
                if($base_spu->seasonal_style==2){
                    $style=3;
                }
            }
            if($t->contract_class==5){$style=4;}

            $one['style'] = $style;//1：外贸订单；2：冬款电商采购类形；3：夏款电商采购类型；4：采购外发型订单）
            $one['user_cg'] = $user;//采购人
            $one['exw_factory_date'] = $v->report_date;//预计货好时间
            $one['remark_gd'] = $t->memo;//跟单备注
            $one['remark_qc'] = $t->delivery_memo;//QC备注
            $one['counter_num'] = '';//头样实际数量
            $one['revised_num'] = '';//修改样实际数量
            $one['pp_send_num'] = '';//产前样实际数量
            $one['size_num'] = '';//	尺码样实际数量
            $one['shipping_num'] = '';//船头样实际数量
            $one['photo_num'] = '';//拍照样实际数量
            $one['chinese_description'] = '';//中文品名
            $one['chinese_composition'] = '';//中文面料成分
            $one['brand'] = '';//品牌
            $one['destination_port'] = '';//目的港
            $one['loading_port'] = '';//装运港
            $one['size_rule'] = $v->rule;//尺码
            $one['cn_color'] = $v->color_name;//颜色
            $data[$bi][] = $one;
            if($i>($bi*20)){
                $bi++;
                $data[$bi][] =  $one;
                $i++;
            }else{
                $i++;
            }

        }

        $counctrys = db::table('shop as a')->leftjoin('countrys as b','a.country_id','=','b.Id')->where('a.Id',$shop_id)->select('b.name')->first();
        $country = '';
        if($counctrys){
            $country =  $counctrys->name;
        }


        $rem = [];
        foreach ($data as $bi => $bv) {
            # code...
            $post['formData'] = $bv;
            $post['user_add'] = $user;//创建人
            $post['client_name'] =  $supplier;//客户
            $post['country'] =  $country;//国家
            $post['xmly_key'] = $xmly_key;//
            $post['order_no'] = $order_no;//订单号
            $url = 'http://new.onedog.cn/pc/sync/syncXMLYOrder';
            $return = $this->curls($url,http_build_query($post));
            $m = json_decode($return,true);
            if($m['code']==200){
                $rm['code']=200;
                $rm['msg'] = '同步成功';
                $rm['data'] = $post;
                db::table('cloudhouse_contract_total')->where('id',$t->id)->update(['is_onedog'=>1]);
                $rem[] = $rm;
            }else{
                $rm['code']=500;
                $rm['msg']='同步失败';
                $rm['data'] = $post;
                $rm['return'] = $m;
                // $rem[] = $rm;
                return $rm;
            }
        }
      
        return ['code'=>200,'msg'=>'同步成功','data'=>$rem];
       
    }


    private function GetOneDogUserId($user_id){
        $return = '';
        $account = $this->GetUsers($user_id)['account']??'';
        if($account){
            $return = Redis::Hget('onedog:user',$account);
            if(!$return){
                $url = 'http://new.onedog.cn/pc/sync/getUserInfo';
                $post = ['name'=>$account];
                $return = $this->curls($url,$post)??[];
                Redis::Hset('onedog:user',$account,$return);
            }

        }
        return $return;
    }

    private function GetOneDogSupplierId($supplier_no){
        $return = '';
        $supplier = db::table('suppliers')->where('supplier_no',$supplier_no)->first();
        if($supplier){
            $return = Redis::Hget('onedog:supplier',$supplier->name);
            if(!$return){
                $url = 'http://new.onedog.cn/pc/sync/getFactoryInfo';
                $post = ['factory_name'=>$supplier->name];
                $return = $this->curls($url,$post)??[];
                Redis::Hset('onedog:supplier',$supplier->name,$return);
            }
        }
        return $return;
    }
    

    private function curls($url, $post=false, $head=''){
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        
        // 优化curl 速度
        curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); //强制协议为1.0
        curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);//强制使用IPV4协议解析域名
        // 头部
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:')); //头部要送出'Expect: '
        if(!empty($head)){
            curl_setopt($curl, CURLOPT_HTTPHEADER, $head); // 请求头部
        }

        
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
            curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        if(!empty($post)){
            curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
            curl_setopt($curl, CURLOPT_POSTFIELDS, $post); // Post提交的数据包
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 120); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $res = curl_exec($curl); // 执行操作
        
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $res; // 返回数据，json格式
    }


    /**
     * @Desc:新增合同到货计划
     * @return null
     * @author: 严威
     * @Time: 2023/10/27
     */
    public function ContractPlan($params){
        try {
            if (!isset($params['user_id']) || empty($params['user_id'])){
                if (isset($params['token']) && !empty($params['token'])){
                    $users = db::table('users')->where('token',$params['token'])->first();
                    if($users){
                        $params['user_id'] = $users->Id;
                    }else{
                        throw new \Exception('未给定创建人标识！');
                    }
                }else{
                    throw new \Exception('未给定创建人标识！');
                }
            }
            if (!isset($params['contract_no'])){
                throw new \Exception('未给定合同号！');
            }
            if (!isset($params['warehouse_id'])){
                throw new \Exception('未给定仓库！');
            }
            if (!isset($params['box_num']) || $params['box_num'] <= 0){
                throw new \Exception('未给定箱数或给定箱数数值不正确！');
            }
            if (!isset($params['num']) || $params['num'] <= 0){
                throw new \Exception('未给定到货数量或给定到货数量数值不正确！');
            }
            if (!isset($params['plan_start_time']) || !isset($params['plan_end_time'])){
                throw new \Exception('未给定到货时间段！');
            }
            $insert['warehouse_id'] = $params['warehouse_id'];
            $insert['contract_no'] = $params['contract_no'];
            $insert['plan_start_time'] = $params['plan_start_time'];
            $insert['plan_end_time'] = $params['plan_end_time'];
            $insert['addtime'] = date('Y-m-d H:i:s');
            $insert['created_id'] = $params['user_id'];
            $insert['memo'] =  $params['memo'] ?? '';
            $insert['status'] = 0;
            $insert['box_num'] = $params['box_num'];
            $insert['num'] = $params['num'];
            db::beginTransaction();
            $setPlan = DB::table('cloudhouse_contract_plan')
                ->where('contract_no',$insert['contract_no'])
                ->where('warehouse_id', $insert['warehouse_id'])
                ->where('plan_start_time', '<=', $insert['plan_start_time'])
                ->where('plan_end_time','>=', $insert['plan_end_time'])
                ->whereIn('status', [0, 1])
                ->select('id')
                ->first();
            if($setPlan){
                throw new \Exception('已存在同时间段的spu到货计划--'.$insert['contract_no']);
            }
            $in = DB::table('cloudhouse_contract_plan')->insert($insert);
            if(!$in){
                throw new \Exception('新增到货计划失败--'.$insert['contract_no']);
            }
            db::commit();
            return  ['code' => 200, 'msg' => '保存成功！'];
        }catch (\Exception $e){
            db::rollback();// 回调
            return ['code'=>500,'msg'=>'保存失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    /**
     * @Desc:修改合同到货计划
     * @return null
     * @author: 严威
     * @Time: 2023/10/27
     */
    public function ContractPlanUpdate($params)
    {
        try {
            if (!isset($params['user_id']) || empty($params['user_id'])){
                if (isset($params['token']) && !empty($params['token'])){
                    $users = db::table('users')->where('token',$params['token'])->first();
                    if($users){
                        $params['user_id'] = $users->Id;
                    }else{
                        throw new \Exception('未给定创建人标识！');
                    }
                }else{
                    throw new \Exception('未给定创建人标识！');
                }
            }
            if (!isset($params['id'])){
                throw new \Exception('未给定到货计划标识！');
            }
            if (!isset($params['warehouse_id'])){
                throw new \Exception('未给定仓库！');
            }
            if (!isset($params['box_num']) || $params['box_num'] <= 0){
                throw new \Exception('未给定箱数或给定箱数数值不正确！');
            }
            if (!isset($params['num']) || $params['num'] <= 0){
                throw new \Exception('未给定到货数量或给定到货数量数值不正确！');
            }
            if (!isset($params['plan_start_time']) || !isset($params['plan_end_time'])){
                throw new \Exception('未给定到货时间段！');
            }

            $insert['warehouse_id'] = $params['warehouse_id'];
            $insert['plan_start_time'] = $params['plan_start_time'];
            $insert['plan_end_time'] = $params['plan_end_time'];
            $insert['created_id'] = $params['user_id'];
            $insert['memo'] =  $params['memo'] ?? '';
            $insert['box_num'] = $params['box_num'];
            $insert['num'] = $params['num'];
            $insert['status'] = 0;

            db::beginTransaction();
            $setPlan = DB::table('cloudhouse_contract_plan')
                ->where('id', $params['id'])
                ->first();
            if(empty($setPlan)){
                throw new \Exception('到货计划不存在！');
            }
            if($setPlan->status == 1){
                throw new \Exception('到货计划已审核通过状态不可修改！');
            }
            $setPlan = DB::table('cloudhouse_contract_plan')
                ->where('contract_no',$setPlan->contract_no)
                ->where('warehouse_id', $insert['warehouse_id'])
                ->where('plan_start_time', '<=', $insert['plan_start_time'])
                ->where('plan_end_time','>=', $insert['plan_end_time'])
                ->whereIn('status', [0, -1])
                ->where('id', '<>', $params['id'])
                ->select('id')
                ->first();
            if($setPlan){
                throw new \Exception('已存在同时间段的spu到货计划--');
            }
            $in = DB::table('cloudhouse_contract_plan')
                ->where('id', $params['id'])
                ->update($insert);
            if(!$in){
                throw new \Exception('修改到货计划失败');
            }
            db::commit();
            return  ['code' => 200, 'msg' => '保存成功！'];
        }catch (\Exception $e){
            db::rollback();// 回调
            return ['code'=>500,'msg'=>'保存失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    /**
     * @Desc:删除合同到货计划
     * @return null
     * @author: 严威
     * @Time: 2023/10/27
     */
    public function ContractPlanDelete($params){
        $db = DB::table('cloudhouse_contract_plan')->where('id',$params['id'])->first();
        if ($db->status == 1){
            return ['code'=>500,'msg'=>'该到货计划已审核通过，不可删除！'];
        }
        $delete = DB::table('cloudhouse_contract_plan')->where('id',$params['id'])->delete();

        if($delete){
            return ['code'=>200,'msg'=>'删除成功！'];
        }else{
            return ['code'=>500,'msg'=>'删除失败'];
        }
    }

    /**
     * @Desc:查询合同到货计划
     * @return null
     * @author: 严威
     * @Time: 2023/10/27
     */
    public function ContractPlanSelect($params){

        $data = DB::table('cloudhouse_contract_plan')->where('contract_no',$params['contract_no'])->get()->toArray();

        $plan_time = array();
        foreach ($data as $v){
            if(!in_array($v->plan_start_time.'~'.$v->plan_end_time,$plan_time)){
                $plan_time[] = $v->plan_start_time.'~'.$v->plan_end_time;
            }
        }

        $res['data'] = $data;
        $res['plan_time'] = $plan_time;

        return $res;
    }

    public function auditContractPlan($params)
    {
        try {
            if (!isset($params['user_id']) || empty($params['user_id'])){
                if (isset($params['token']) && !empty($params['token'])){
                    $users = db::table('users')->where('token',$params['token'])->first();
                    if($users){
                        $params['user_id'] = $users->Id;
                    }else{
                        throw new \Exception('未给定创建人标识！');
                    }
                }else{
                    throw new \Exception('未给定创建人标识！');
                }
            }
            $controller = new Controller();
            $power = $controller->powers(['user_id' => $params['user_id'], 'identity' => ['audit_contract_plan']]);

            if (!$power['audit_contract_plan']){
                throw new \Exception('您无审核权限！');
            }
            if (!isset($params['id'])){
                throw new \Exception('未给定合同到货标识！');
            }
            $contractPlanMdl = db::table('cloudhouse_contract_plan')
                ->where('id', $params['id'])
                ->first();
            if (empty($contractPlanMdl)){
                throw new \Exception('合同到货数据不存在！');
            }
            if ($contractPlanMdl->status != 0){
                throw new \Exception('该合同到货非待审核不可审核！');
            }
            if (!isset($params['audit']) || !in_array($params['audit'], [-1, 1])){
                throw new \Exception('未给定审核标识或给定标识不正确！');
            }
            if ($params['audit'] == -1){
                if (!isset($params['audit_memo']) || empty($params['audit_memo'])){
                    throw new \Exception('未给定审核拒绝意见！');
                }
            }
            $update = db::table('cloudhouse_contract_plan')
                ->where('id', $params['id'])
                ->update([
                    'status' => $params['audit'],
                    'audit_memo' => $params['audit_memo'] ?? '',
                    'audited_at' => date('Y-m-d H:i:s'),
                    'audit_id' => $params['user_id'],
                ]);
            if (empty($update)){
                throw new \Exception('审核信息保存失败！');
            }
            return ['code' => 200, 'msg' => '审核成功！'];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '审核失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }


}